Nginx自动屏蔽异常IP脚本

goshawkcv 贡献于2012-06-25

作者 SongJiao  创建于2011-12-01 01:27:00   修改者SongJiao  修改于2011-12-01 01:41:00字数1671

文档摘要:思路:以小时为单位,每小时统计一次上个小时内access日志里访问次数大于N的IP,将IP存成文本BLACKIPLIST,格式为denyxxx.xxx.xxx.xxx,然后在nginx.conf文件里的location里添加includeBLACKIPLIST;
关键词:

Nginx自动屏蔽异常IP脚本 思路: 以小时为单位,每小时统计一次上个小时内access日志里访问次数大于N的IP,将IP存成文本BLACKIPLIST,格式为deny xxx.xxx.xxx.xxx,然后在nginx.conf文件里的location里添加include BLACKIPLIST;重载nginx。 STEP1:制作nginx日志分割脚本 [@WEB_3-47 sbin]# cat /usr/local/nginx/logs/splitlog.sh #!/bin/bash date=`date +%Y%m%d%H` cat /usr/local/nginx/logs/host.access.log>>/usr/local/nginx/logs/host.access.log.$date >/usr/local/nginx/logs/host.access.log 在crontab里添加: */1 * * * * /usr/local/nginx/logs/splitlog.sh >/dev/null 2>&1 STEP2:修改nginx.conf,include IP屏蔽列表文件 location / { include BLACKIPLIST; proxy_next_upstream error timeout http_503 http_500 http_502 http_504; proxy_pass http://account; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; } 这里面的include BLACKIPLIST的意思是将/usr/local/nginx/conf/下的BLACKIPLIST文件包含到配置文件里。 STEP3:编写生成BLACKIPLIST文件的脚本 [@WEB_3-47 sbin]# cat /usr/local/nginx/sbin/cc_detect.sh #!/bin/sh #BALCK IP LIST BLACKIPLIST=/usr/local/nginx/conf/BLACKIPLIST #TEMP BLACKIPLIST TEMP_BLACKIPLIST=/tmp/TEMP_BLACKIPLIST #TEMP BLACKIPLIST2 TEMP_BLACKIPLIST2=/tmp/TEMP_BLACKIPLIST2 #LAST HOUR ACCESS LOG LASTHOURLOG=/usr/local/nginx/logs/host.access.log.`date --date="2 hour ago" +%Y%m%d%H` if [ ! -f "$LASTHOURLOG" ]; then echo "ERROR! $LASTHOURLOG not exists!" exit fi if [ ! -f "$BLACKIPLIST" ]; then touch "$BLACKIPLIST" fi more $LASTHOURLOG |awk '{++S[$1]}END{for(a in S)if(S[a]>5000)print "deny "a";"}' >$TEMP_BLACKIPLIST cat $TEMP_BLACKIPLIST $BLACKIPLIST |sort -u >$TEMP_BLACKIPLIST2 mv $TEMP_BLACKIPLIST2 $BLACKIPLIST /usr/local/nginx/sbin/nginx -t if [ $? -eq 0 ]; then kill -HUP `cat /usr/local/nginx/logs/nginx.pid` fi 将脚本添加到定时任务: 31 * * * * /usr/local/nginx/sbin/cc_detect.sh >/dev/null 2>&1 #每周清理一次异常IP列表 13 14 * * 1 >/usr/local/nginx/conf/BLACKIPLIST >/dev/null 2>&1

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 3 金币 [ 分享文档获得金币 ] 3 人已下载

下载文档