练习题3

# 公司服务器,经常被别人攻击,要写个监控nginx日志的脚本,每分钟运行一次,如果这一分钟内同一个ip请求次数超过200次,加入黑名单,nginx日志每一行的格式如下:
# 46.161.9.44 - - [23/Jun/2017:03:17:37 +0800] "GET /bbs/forum.php?mod=forumdisplay&fid=2 HTTP/1.0" 200 48260 "http://aaaa.bbbbb.com/bbs/forum.php?mod=forumdisplay&fid=2" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" "-"
# 46.161.9.44 - - [23/Jun/2017:03:17:39 +0800] "GET /bbs/forum.php?mod=forumdisplay&fid=2 HTTP/1.0" 200 46200 "http://aaaa.bbbbb.com/bbs/forum.php?mod=forumdisplay&fid=2" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" "-"

def log_monitor():
import time
pin = 0
while True:
ips = [] #存放所有ip
blk_set = set () #存放黑名单ip
with open('aa.log') as fr:
fr.seek(pin)
for line in fr:
ip = line.split()[0] #split默认以空格分隔
ips.append(ip)
if ips.count(ip) > 200:
blk_set.add(ip) #因为集合去重,只会存在一个记录
for ip in blk_set:
print('加入黑名单:%s'%ip)
pin = fr.tell() #记录读完的指针位置
time.sleep(60)

log_monitor()

posted on 2019-05-16 09:36  奥喵  阅读(150)  评论(0编辑  收藏  举报

导航