根据web访问日志,封禁请求量异常的IP,如IP在半小时后恢复正常,则解除封禁
规则:之前1分钟内访问的ip次数大于100时禁止访问;30分钟后解封
代码:
#!/bin/bash
grep $(date -d "1 minute ago" +%d/%b/%Y:%H:%M) /usr/local/nginx/logs/access.log | awk {'print $1'} |sort|uniq -c| awk '{if($1>100){print $2}}' > "iplist.txt"
while read line;do
iptables -I INPUT -p tcp -s $line -j DROP
echo $(date +%s) " " $line >> "disiplist.txt"
done < iplist.txt
#以下是解封
n=$(date +%s)
icount=0
while read line;do
t=$(echo $line | cut -d " " -f1)
ip=$(echo $line | cut -d " " -f2)
echo $ip
let x=n-t
if [ $x -gt 1800 ]; then
es=$(iptables -L INPUT --line-numbers | grep $ip | wc -l)
if [ $es -gt 0 ]; then
en=$(iptables -L INPUT --line-numbers | grep $ip | head -1| cut -d " " -f1)
echo $en
iptables -D INPUT $en
let ii=ii+1
fi
fi
done < disiplist.txt
#echo $ii
if [ $ii -gt 0 ]; then
sed -i "1,${ii}d" disiplist.txt
fi