前文写了一个添加ip的python脚本,https://www.willnet.net/index.php/archives/104/
现在做一个自动添加方案,以阿里云日志服务收集nginx日志为例,目的是自动屏蔽每15分钟请求超过2500次的IP地址
1,阿里云日志服务新建搜索

* | select remote_addr,count(*)  as count group by remote_addr order by count desc limit 1

保存上面的搜索为快速查询
2,配置nginx新站点,反代8088端口,配置日志输出为
nginx.conf

log_format log-alarm-access '$request_body '

example.com.conf

server {
listen 80;
server_name example.com;
index index.html index.htm index.php;
  if ($http_x_forwarded_proto = "http") {
    return 307 https://$host$request_uri;
  }


location /requestoverlimit {
  proxy_pass         http://localhost:8088;
  proxy_redirect     off;
  proxy_set_header   Host              $host;
  proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
  proxy_set_header   X-Forwarded-Proto $scheme;
  access_log /var/log/nginx/example.com.access.log log-alarm-access;
}
}

3,新建python脚本
server.py

#!/usr/bin/env python
"""
Very simple HTTP server in python.
Usage::
    ./dummy-web-server.py [<port>]
Send a GET request::
    curl http://localhost
Send a HEAD request::
    curl -I http://localhost
Send a POST request::
    curl -d "foo=bar&bin=baz" http://localhost
"""
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer

class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.wfile.write("<html><body><h1>hi!</h1></body></html>")

    def do_HEAD(self):
        self._set_headers()
        
    def do_POST(self):
        # Doesn't do anything with posted data
        self._set_headers()
        self.wfile.write("OK")
        
def run(server_class=HTTPServer, handler_class=S, port=8088):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print 'Starting httpd...'
    httpd.serve_forever()

if __name__ == "__main__":
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

4,启动python server.py,并添加服务器启动命令到rc.local开机启动
5,阿里云日志服务把1里面保存的快速查询另存为告警,webhook地址填上面新建的网址,如图
另存为告警
6,新建定时任务,每五分钟执行

*/5 * * * *  tail -n 1 /var/log/nginx/example.com.access.log|awk -F ":" '{print $9}'|awk -F "]" '{print $1}'|xargs python /root/aliyun/scripts/addaclentry.py >> /var/log/autoaddblacklist/autoaddblacklist.log 2>&1 

7,查看访问控制黑名单列表

ps:一键脚本,对比上一次IP地址是否已经添加到黑名单

#! /bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

function sameip(){
        lastip=$(cat /root/aliyun/server/lastip.txt)
        currentip=$(tail -n 1 /var/log/nginx/example.com.access.log|awk -F ":" '{print $12}'|awk -F "]" '{print $1}')
        if [ "$currentip"x != "$lastip"x ];then
                echo $currentip >/root/aliyun/server/lastip.txt
                cat /root/aliyun/server/lastip.txt|xargs python /root/aliyun/scripts/addaclentry.py >> /var/log/autoaddblacklist/autoaddblacklist.log 2>&1
        else
                date "+%Y-%m-%d %H:%M:%S" >> /var/log/autoaddblacklist/autoaddblacklist.log && echo "same ip address" >> /var/log/autoaddblacklist/autoaddblacklist.log
        fi
}

sameip

crontab定时,每分钟执行一次

* * * * * /root/aliyun/scripts/sameip.sh