#!/usr/bin/env python # -*- coding: utf-8 -*- # import os import time threshold = 120 # 获取前一分钟的结果 date = time.strftime('%Y:%H:%M', time.localtime(time.time()-60)) filename = '/usr/share/nginx/logs/geokon.access.log ' def popen(command): return os.popen(command).readlines() def main(): with open('/tmp/ipset.txt', 'a') as f: f.write('%s: 日志搜索...........\n' % (date)) command = "grep %s %s | awk '{counts[$1]++}; END {for(url in counts) print counts[url], url}'" % (date, filename) for ip in popen(command): num, ipaddr = ip.split(' ') num, ipaddr = int(num), ipaddr.strip() # 第一个值是整型, 第二个值应当去掉空格 if num >= threshold: if all(popen('ipset list | grep %s' % (ipaddr))): # 如果不为true 那就添加 f.write('每分钟大于%s次 地址: %s 将被禁止访问' % (threshold, ipaddr)) popen('ipset add blacklist %s timeout 3600 &>/dev/null' % (ipaddr)) elif num >= 50: f.write('访问次数 %s: %s\n' % (num, ipaddr)) f.write('日志搜索结束.................\n\n\n') if __name__ == '__main__': main()