2014-01-31 50 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地址。