nginx自动封锁爬虫

随着python的流行,现在爬虫无处不在,每个网站都有数据泄露的风险。我们公司的官网每天访问量巨大,远超正常业务量。经过小编1天的劳动,终于圆满解决,大体步骤如下:

1. 修改nginx日志配置,使日志第一列打印客户端ip。

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"'
                        '$upstream_addr ';

2. 有了源IP就可进行日志分析。下面结果第一列是访问次数,后面一列是访问ip,后面还有大量的腾讯云ip未罗列。

[root@localhost ~]# cat access_2017-05-30.log | grep FlightSearch.do|awk '{print $1}' | sort | uniq -c | sort -k 1 -n -r | head -234
  24957 119.39.169.185        湖南省郴州市
   5735 139.199.210.193        腾讯云
   5640 123.207.188.117        腾讯云
   5636 115.159.223.175
   5619 111.230.135.142
   5613 118.89.224.133
   5609 111.230.139.30
   5608 123.207.19.72
   5605 123.207.188.126

3. 经与业务人员确认,我们公司于以上ip均无业务往来。在nginx.conf文件中增加黑白名单配置:

                include /u01/nginx/conf/whitelist/white*.conf;
                include /u01/nginx/conf/blacklist/black*.conf;

白名单通过业务部门获取后手工添加

allow 172.16.0.0/16;
allow 172.18.18.0/24;

4.定时任务每10分钟统计日志中访问高的ip进行封锁(前提access.log每天自动分割,不然文件巨大必然影响服务器性能):

*/10 * * * * /u01/nginx/conf/black.sh

#!/bin/bash
    nginx_home=/u01/nginx
    log_path=$nginx_home/logs/b2c
        cat $log_path/access.log\
        |grep -E "GET /showIndex.do|POST /FlightSearch.do"\
        |awk '{print $1}'\
        |sort|uniq -c|sort -rn \
        |awk '{if($1>20)print "deny "$2";"}' >$nginx_home/conf/blacklist/black.`date +%F`.conf
        $nginx_home/sbin/nginx -s reload

/u01/nginx/conf/blacklist目录下会根据天生产黑名单文件。

 

以上方法只能应付初级爬虫,高级爬虫能够进行ip代理,还需要从程序本身进行防范。

posted on 2018-03-30 15:33  zuooo  阅读(393)  评论(0编辑  收藏  举报

导航