脚本实现nginx添加ip到黑名单

防止ip攻击(补充:配合crontab,比如每10分钟执行一次,假设10分钟内访问次数超过设定阈值的,就可以自动加入nginx的block ip名单中)

#!/usr/bin/python
#--*coding:utf-8 -*-


import re
import commands[]
import os
import sys
import time
import subprocess 


pattern = r"(\d+)\s+([0-9\.]{7,15})"
REQUESTCOUNT = 200
BLOCKFILE = '/usr/local/nginx/conf/blockip.conf'
#当前日期时间
currenttime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
currentUnixtime = time.time()
def restartservice():
    #ret = os.system("sudo service php-fpm restart")
    (status, output) = commands.getstatusoutput('/usr/local/nginx/sbin/nginx -s reload')
    print ""
def writeLogs(line):
    text = str(line)
    fp = open('/data/wwwlogs/blockip.log','a');
    fp.write(currenttime+"\t"+text+"\n")
    fp.close


def writeBlock(line,counts):
    ip = str(line)
    if ip and len(ip) > 0 :
        fp = open(BLOCKFILE,'a');
        s = "\ndeny\t"+ip+";\t#"+currenttime+"\t"+counts
        fp.write(s)
        print s
        writeLogs(s)
        fp.close

def removeExpiredData(content):
    rpattern = r"\#([0-9\-]{10}\s+[0-9\:]{8})"
    rows = []
    arr = content.split("\n")
    for row in arr:
        matches = re.findall(rpattern, row, re.M)
        if matches:
                format = '%Y-%m-%d %H:%M:%S'
                expiredTime = time.mktime(time.strptime(matches[0], format))
                now = time.time()
                if now - expiredTime  < 86400 :
                        rows.append(row) 
        else:
                if row:
                        rows.append(row)
    result = "\n".join(rows)
    fp = open(BLOCKFILE,'w');
    fp.write(result)
    fp.close
    return result
def blocklist():
    fp =  open(BLOCKFILE)
    content = ''
    try:
        content = removeExpiredData(fp.read())
        #for line in content:
        #    print line 
    finally:
        fp.close()
    return content
def analyzelog(lists,blist):
    counts = lists[0]
    ipaddr = lists[1]
    if int(counts) > REQUESTCOUNT:
        ret = blist.find(ipaddr)
        if ret == -1:
            writeBlock(ipaddr,counts)

def monitorlog():
        blist = blocklist()
        s = "tail -n20000 /data/wwwlogs/access_proxy.log | grep -v 403 | awk '{print $1}'|sort|uniq -c|sort -rn | head"
        p=os.popen(s)
        x=p.readlines()
        for line in x:
                matchObj = re.findall(pattern, line, re.M)
                if line and len(matchObj) > 0:
                        analyzelog(matchObj[0],blist)
        restartservice()
if __name__ == "__main__":
    monitorlog()
posted @   从雍和宫走到电影学院  阅读(124)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示