【问题标题】:Block all ips in files [closed]阻止文件中的所有 ip [关闭]
【发布时间】:2014-01-31 12:33:04
【问题描述】:

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

一个一个地阻止 ips 的工作量很大而且是不切实际的 (iptables -I INPUT -s xxx.xxx.xxx.xxx -j DROP)。 我的想法是是否可以一次阻止 error.log 文件中的所有 ip。

是否可以编写脚本来执行此操作?

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
...

【问题讨论】:

    标签: linux bash ubuntu firewall iptables


    【解决方案1】:

    试试下面的方法

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

    【讨论】:

    • 看起来不错,但是因为 bash 的正则表达式是贪婪的,'client '(.*)':' 的匹配将包括所有文本,直到行中的最后一个冒号,并且 OP 的 error.log 有几个。 'client '([^:]+) 可能会更好。
    • @John1024 哎呀,用]而不是:测试它,忘了还有其他冒号。如果您想将其发布为答案,我将删除我的,因为它在技术上不起作用。
    • 这是一个好心的提议,但是,不,你的回答很好:+1。
    【解决方案2】:

    使用 awk

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

    先运行不带|sh的awk命令,确认输出正确,再添加|sh屏蔽IP。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 2015-12-25
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 2019-12-18
      • 2016-06-09
      相关资源
      最近更新 更多