2014-01-31 28 views
0

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

被大量的工作一个接一个地阻塞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

尝试类似下面

#!/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

看起来不错,但是,因为bash的正则表达式很贪婪,所以''client'(。*)'的匹配将包含所有文本直到行中的最后一个冒号,而OP的error.log有几个。 ''client'([^:] +)'可能会更好。 – John1024

+0

@ John1024 Woops,用']'而不是':'测试过,忘记还有其他冒号。如果你想把它作为答案发布,我会删除我的,因为它在技术上不起作用。 – BroSlow

+0

这是一种优惠,但是,不,您的回答很好:+1。 – John1024

0

使用AWK

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

而不|sh首先要确认该输出运行awk命令是正确的,然后添加|sh阻止的IP地址。