这几天每天访问量一台ip居然可以到1000W,把我服务器撑爆了,所以做了个自动加ip黑名单的定时任务脚本。
首先配置一个shell脚本
addblackip.sh
#!/bin/sh
#是否需要reload nginx
needRefresh=false
#把黑名单的配置文件读取一下
blackFile=/xxx/nginx/blockips.conf
blackIp=`cat $blackFile`
#把nginx的访问日志读取汇总统计倒序排列,并且只拿访问量大于5W的数据
#awk针对32位的linux可能大数据文件会报内存不够,可以改成tail的语句,网上应该一搜一大把,这边就不写了
ip_count=`awk '{print $1}' /xxx/log/nginx/access.log |sort |uniq -c|sort -rn |awk '{if($1>50000) {print $2}}'`
for ip in $ip_count;
do
vtext=" $ip;"
#拿访问量大的ip与黑名单配置正则比较,如果存在就不处理,存在则需要reload nginx
#为了防止匹配错误,特别在前后分别加了" "、";"
if [[ $blackIp =~ $vtext ]];then
echo "$ip exist"
else
needRefresh=true
echo "deny $ip;" >> $blackFile
fi
done
if [ $needRefresh == true ];then
xx/xx/nginx -s reload
echo "nginx reload"
fi
这边加echo主要是为了单独调试可以看日志
配置定时任务
指令可查看现有定时任务
[root]crontab -l
编辑增加定时任务,日志和错误全都不记录
[root]crontab -e -u root
0 */1 * * * /xxx/addblackip.sh >/dev/null 2>&1