从apache的错误日志中找出恶意ip,并通过iptables过滤

查看apache的错误日志(grep "File does not exist" /var/log/httpd/error_log)的时候发现有大量类似这样的内容:

[Wed Feb 18 14:01:18 2009] [error] [client 58.22.112.116] File does not exist: /var/www/html/web.rar
[Wed Feb 18 14:01:18 2009] [error] [client 58.22.112.116] File does not exist: /var/www/html/web.zip
[Wed Feb 18 14:01:18 2009] [error] [client 58.22.112.116] File does not exist: /var/www/html/www.rar
[Wed Feb 18 14:01:18 2009] [error] [client 58.22.112.116] File does not exist: /var/www/html/www.zip
[Wed Feb 18 14:01:19 2009] [error] [client 58.22.112.116] File does not exist: /var/www/html/wwwroot.rar
[Wed Feb 18 14:01:19 2009] [error] [client 58.22.112.116] File does not exist: /var/www/html/wwwroot.zip


    似乎有人在恶意扫描系统,于是想根据这些File does not exist的个数来把这些恶意攻击服务的ip地址给找出来,然后用iptables给过滤掉?技术上来说是当然可以,于是就用awk先把ip地址给弄出来。于是写了个命令:

awk '/File does not exist/ { printf $8 " " }' /var/log/httpd/error_log* | sort -k1n | uniq -d -c | tr "]" " " | awk '$1 > 50 {printf $2 " "}' >/tmp/iptables.txt 2>/dev/null


uniq是用来删除重复行和统计重复行出现的次数的,tr把替换掉],最后一个是把出现次数比较多的ip地址给选出来。那个50是表示出现 超过50次“File does not exist”的IP地址,基本上可以被定位为扫描或者攻击IP(如果有多个文件,可以使用error_log*,如果只有一个文件,直接写成 error_log就可以了)。

使用如下的脚本文件,则会自动将此内容写入iptables防火墙

#先创建iptable的chain,然后将他插入到INPUT的最前方,防止失效
iptables -N BlockIP
iptables -I INPUT -j BlockIP

#执行如下命令,将攻击IP写入临时文件(如果是第二次做,就将error_log*后面的*去掉即可)
awk '/File does not exist/ { printf $8 " " }' /var/log/httpd/error_log* | sort -k1n | uniq -d -c | tr "]" " " | awk '$1 >200 {printf $2 " "}' >/tmp/iptables.txt 2>/dev/null

#使用如下的脚本,将这些IP写入防火墙的block列表,直接DROP

#!/bin/bash

for bip in $(cat /tmp/iptables.txt )
do
    # 判断是否已经被block
    /sbin/iptables-save |grep INPUT |grep $bip >/dev/null 2>&1
    # 如果返回值不为0,表示不存在,可以添加进入
    if [ $? -ne 0 ]; then
      /sbin/iptables -I INPUT -s $bip -j DROP >/dev/null 2>&1
      date >>/tmp/iptables_blockip.txt
      echo $bip >>/tmp/iptables_blockip.txt
    fi
done

iptables-save

service iptables save