需求:監控日誌,若是有攻擊,就把ip加入黑名單php
分析:html
一、打開日誌文件,讀取文件中的全部的內容app
二、提取內容中的ipgoogle
三、把ip放入到列表中去,在用set去重,獲得獨立不一樣的ip數指針
四、循環set中的ip,到list中去進行ip個數的統計,超過50次的加入到黑名單日誌
日誌信息以下:htm
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 timecount=0 #初始的文件指針設置爲0while 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)