阻止文件中的所有ips

时间:2014-01-31 02:54:17

标签: linux bash ubuntu firewall iptables

我有一个测试服务器,它不断接收阻止我的apache服务器的请求(命中)。

逐步阻止ips进行大量工作并且不切实际(iptables -I INPUT -s xxx.xxx.xxx.xxx -j DROP)。 我认为是否可以立即阻止error.log文件中的所有ips。

可以制作一个脚本来执行此操作吗?

error.log中

[Fri Jan 31 02:39:54.827551 2014] [:error] [pid 2442] [client 198.98.104.231:2078] script '/var/www/banner_160x600.php' not found or unable to stat, referer: ://www.beautifulstarrysky.com/index.php?option=com_mailto&tmpl=component&link=b9131f144a565bd8b091fd4d5699cfe18c2b60eb
[Fri Jan 31 02:39:54.967606 2014] [:error] [pid 2543] [client 23.19.50.19:2465] script '/var/www/header53621.php' not found or unable to stat
[Fri Jan 31 02:39:54.986088 2014] [:error] [pid 2481] [client 192.151.152.245:3851] script '/var/www/ads.php' not found or unable to stat, referer: http://www.fashionwomenclothes.com/index.php?option=com_content&view=article&id=4772:2013-10-26-01-03-30&catid=20:clothes-shops&Itemid=103
...

2 个答案:

答案 0 :(得分:2)

尝试以下内容

#!/bin/bash
while read -r line; do
  [[ $line =~ 'client '([^:]+) ]] && iptables -I INPUT -s "${BASH_REMATCH[1]}" -j DROP
done < error.log

这将匹配"client "和冒号之间的所有内容作为ip(请参阅@John1024关于以这种方式执行此操作然后只匹配冒号的注释),使用BASH_REMATCH

   BASH_REMATCH
          An  array  variable  whose members are assigned by the =~ binary
          operator to the [[ conditional command.  The element with  index
          0  is  the  portion  of  the  string matching the entire regular
          expression.  The element with index n  is  the  portion  of  the
          string matching the nth parenthesized subexpression.  This vari‐
          able is read-only.

答案 1 :(得分:0)

使用awk

awk '/error/{split($10,a,":");printf "iptables -I INPUT -s %s -j DROP\n", a[1]}' file |sh

首先运行不带|sh的awk命令确认输出是否正确,然后添加|sh以阻止IP。