脚本功能
封禁当天访问次数超过1000的ip
定时任务
[root@localhost tool]$ sudo crontab -u root -l
*/10 * * * * /data/tool/nginx_black_ip.sh > /data/tool/logs/nginx_black_ip.log
防火墙设置
firewall-cmd --permanent --zone=public --new-ipset=blacklist --type=hash:net
firewall-cmd --permanent --zone=public --add-rich-rule="rule family=ipv4 source ipset=blacklist drop"
firewall-cmd --reload
脚本如下
#!/bin/bash
LogDir='/usr/local/nginx/logs/'
WorkDir='/data/tool'
#统计日志中访问次数超过1000的ip
awk '{a[$1]+=1}END{for(ip in a){if(a[ip]>1000) print ip}}' ${LogDir}.access.log > ${WorkDir}/ip/black_ip.txt
#将不在nginx白名单的ip加入到防火墙黑名单中
for ip in `cat ${WorkDir}/ip/black_ip.txt`
do
if [[ `grep -c $ip ${WorkDir}/ip/white_ip.txt` -eq 0 && `firewall-cmd --ipset=blacklist --get-entries | grep -c $ip` -eq 0 ]];then
echo $ip
firewall-cmd --permanent --zone=public --ipset=blacklist --add-entry=$ip
firewall-cmd --reload
fi
done