需求:监控日志,如果有攻击,就把ip加入黑名单
分析:
1、打开日志文件,读取文件中的所有的内容
2、提取内容中的ip
3、把ip放入到列表中去,在用set去重,得到独立不同的ip数
4、循环set中的ip,到list中去进行ip个数的统计,超过50次的加入到黑名单
日志信息如下:
178.210.90.90 - - [04/Jun/2017:03:44:13 +0800] "GET /wp-includes/logo_img.php HTTP/1.0" 302 161 "http://nnzhp.cn/wp-includes/logo_img.php" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.99 Safari/533.4" "10.3.152.221" 178.210.90.90 - - [04/Jun/2017:03:44:13 +0800] "GET /blog HTTP/1.0" 301 233 "http://nnzhp.cn/wp-includes/logo_img.php" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.99 Safari/533.4" "10.3.152.221" 178.210.90.90 - - [04/Jun/2017:03:44:15 +0800] "GET /blog/ HTTP/1.0" 200 38278 "http://nnzhp.cn/wp-includes/logo_img.php" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.99 Safari/533.4" "10.3.152.221" 66.249.75.29 - - [04/Jun/2017:03:45:55 +0800] "GET /bbs/forum.php?mod=forumdisplay&fid=574&filter=hot HTTP/1.1" 200 17482 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" "-" 37.9.169.20 - - [04/Jun/2017:03:47:59 +0800] "GET /wp-admin/security.php HTTP/1.1" 302 161 "http://nnzhp.cn/wp-admin/s
import time
count=0 #初始的文件指针设置为0
while True:
ip_list = [] #每次循环时把列表清空,因为是按1分钟进行统计的
with open("access.log","r",encoding="utf-8") as fr:
fr.seek(count) #根据文件指针进行文件内容读取
for line in fr: #循环拿每一行内容
ip_list.append(line.split("-")[0]) #取每一行的ip
count=fr.tell() #读完之后更新文件的指针
for ip in set(ip_list): #循环读取集合中的ip并到列表中进行统计
if ip_list.count(ip)>50:
print("把ip为%s的加入到黑名单"%ip)
fr.close() #最后关闭文件句柄
time.wait(60)