标签 黑名单 下的文章

阿里云负载均衡访问控制(黑名单)自动添加IP的方法(续)

https://www.willnet.net/index.php/archives/105/
上文使用了阿里云日志服务的告警,由于告警有一些局限,比如最长只能统计60分钟的日志,最短查询间隔5分钟等,现在使用阿里云日志服务的cli替代告警。
首先需要安装日志服务cli

pip install -U aliyun-log-cli

然后编写脚本
autoaddblacklist.sh

#! /bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
ALIYUN_LOG_CLI_ACCESSID=
ALIYUN_LOG_CLI_ACCESSKEY=
ALIYUN_LOG_CLI_ENDPOINT=cn-beijing.log.aliyuncs.com
export ALIYUN_LOG_CLI_ACCESSID ALIYUN_LOG_CLI_ACCESSKEY ALIYUN_LOG_CLI_ENDPOINT
function autoaddblacklist(){
    nowtime=$(date "+%Y-%m-%d %H:%M:%S %Z")
        last5minutestime=$(date -d '5 minutes ago' "+%Y-%m-%d %H:%M:%S %Z")
    searchresult=$(aliyun log get_log_all --project="www" --logstore="www-nginx-access" --query="* | select remote_addr,count(*)  as count group by remote_addr order by count desc limit 1" --from_time="$last5minutestime" --to_time="$nowtime" --jmes-filter="join('\n', map(&to_string(@), @))")
    lastip=$(cat /root/aliyun/tmp/lastip.txt)
    currentip=$(echo $searchresult | awk -F "[\"]" '{print $16}')
    count=$(echo $searchresult | awk -F "[\"]" '{print $4}')
    if [ "$count" -gt 1000 ] && [ "$currentip"x != "$lastip"x ] ;then
        echo $currentip >/root/aliyun/tmp/lastip.txt
        echo $currentip|xargs python /root/aliyun/scripts/addaclentry.py >> /var/log/aliyun-log-alarm/www/autoaddblacklist.log 2>&1
        curl -H "Content-type: application/json" -X POST -d '{"text": "found ip:'"${currentip}"' request: '"${count}"' over 1000 in 5min,added to the www blacklist."}' https://example.com/incoming/xxxxx-xxxx-xxxx
    else
        date "+%Y-%m-%d %H:%M:%S" >> /var/log/aliyun-log-alarm/www/autoaddblacklist.log && echo "nothing to do" >> /var/log/aliyun-log-alarm/www/autoaddblacklist.log
    fi
}

autoaddblacklist

按需求定时执行上面的脚本就行了

阿里云负载均衡访问控制(黑名单)自动添加IP的方法

前文写了一个添加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