There is a access.log log, formatted as follows, with each line starting with an IP address:
1. Demand:
#1, if you access more than 200 times within the same IP address 60s, add IP to blacklist
#需求分析:
#1, 60 seconds to read a file
#2, split, take the first element, IP address
#3, add all the IP to a list, if the IP number more than 200 times, blacklist
Import time
Point = 0 #文件指针
While True:
IPS = [] #存放所有的ip地址
Blk_set = set () #存放需要加入黑名单ip
With open (' Access.log ', encoding= ' utf-8 ') as F:
F.seek (Point)
For line in F:
ip = line.split () [0]
Ips.append (IP)
#10.125.1.1
If Ips.count (IP) >200:
Blk_set.add (IP)
For IP in Blk_set: #这里是因为防止ip重复加入黑名单 because the collection is de-heavy, there is no duplicate IP inside
#os. System (' Jiaurru%s '%ip) #挨个将集合中的信息 blacklist
Print (' Add blacklist%s '%ip)
Point = F.tell ()
Time.sleep (#隔30s) monitoring once
python-Monitoring Log Exercise