根据 nginx 日志查询访问过多 ip 并加入黑名单
打开 nginx 配置文件/usr/local/nginx/conf/nginx.conf
,http下加入配置;
include blockip.conf
在/etc/cron.hourly下添加脚本 blockip 并赋予可执行权限
chmod 755 blockip
脚本内容:
#!/bin/bash blockip=/usr/local/nginx/conf/blackips.conf access=/usr/local/nginx/logs/access.log for ip in $(awk '{cnt[$1]++;}END{for(i in cnt){printf("%s\t%s\n", cnt[i], i);}}' ${access} | awk '{if($1>50000) print $2}') do echo "deny ${ip};" >> $blockip echo "block ip : ${ip}" >> /usr/local/nginx/logs/nginx_deny.log done /usr/local/nginx/sbin/nginx -s reload
默认每天执行,执行后会添加执行日志到/usr/local/nginx/logs/nginx_deny.log;
解封脚本
在/etc/cron.weekly下添加脚本 cleanBlockip,权限同上;
#!/bin/bash blockip=/usr/local/nginx/conf/blackips.conf > ${blockip} /usr/local/nginx/sbin/nginx -s reload
每周自动清除黑名单;
留言