#!/bin/bash
#Problem:add attacker's ipaddress from log of apapche to iptables
#History:2010/05/28 written
#-------get datetime--------
year=`date +%Y`
month=`date +%b`
day=`date +%d`
hour=`date +%H`
minute=`date +%M`
#-------count the datetime of one minute ago--------
one_minute_time=`expr $minute - 1`
if [ $one_minute_time -lt 10 ];then
one_minute_time="0$one_minute_time"
#-------count the datetime of two minute ago--------
fi
two_minute_time=`expr $minute - 2`
if [ $two_minute_time -lt 10 ];then
two_minute_time="0$two_minute_time"
fi
#echo "$one_minute_time"
#echo "$two_minute_time"
#-------get information from Apache log in nearly three minutes--------
now_minute="$day/$month/$year:$hour:$minute"
if [ $one_minute_time -gt 0 ];then
one_minute_ago="$day/$month/$year:$hour:$one_minute_time"
fi
if [ $two_minute_time -gt 0 ];then
two_minute_ago="$day/$month/$year:$hour:$two_minute_time"
fi
cat access_log | grep $now_minute > /tmp/test.txt
if [ $two_minute_time != "" ];then
cat access_log | grep $two_minute_ago >> /tmp/test.txt
fi
if [ $one_minute_time != "" ];then
cat access_log | grep $one_minute_ago >> /tmp/test.txt
fi
#--------get visited IP----------
test_line=`cut -d" " -f1 /tmp/test.txt | wc -l`
cut -d" " -f1 /tmp/test.txt > /tmp/temp.txt
cat /tmp/temp.txt | sort > /tmp/IPs.txt
#--------count the different IP visition times---------------------------------------------------
#--------if visition times counted over 30 times,and then add the IP to iptables rule------------
#--------else do nothink-------------------------------------------------------------------------
while [ $test_line -gt 0 ]
do
check_ip=`sed -n "1"p /tmp/IPs.txt`
visit_num=`cat /tmp/IPs.txt | grep $check_ip | wc -l`
echo "date:$year/$month/$day"
echo "time:$hour:$two_minute_time-$hour:$minute"
echo "IP:$check_ip"
echo "visited times=`cat /tmp/IPs.txt | grep $check_ip | wc -l`"
if [ $visit_num -gt 30 ];then
if [ `iptables -L | grep $check_ip | wc -l` -eq 0 ];then
iptables -I INPUT -p tcp --dport 80 -s $check_ip -j DROP
echo "this ipaddress is attacking!!"
echo "so add the ipaddress to iptables rule!!"
else
echo "this ipaddress has added to iptable rule!"
fi
fi
cat /tmp/IPs.txt | grep -v $check_ip | sort > /tmp/temp.txt
cat /tmp/temp.txt > /tmp/IPs.txt
test_line=`cat /tmp/IPs.txt | wc -l`
echo ""
done
ps:此脚本是针对apache访问日志所做的智能阻挡脚本....