python_监控日志(将频繁访问的ip加入黑名单)
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
######################
知识点:
1.str.split(str="", num=string.count(str)).
str为分隔符,默认为空字符或回车
num为分隔次数
返回值:返回分隔后的列表
如:
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( );
print str.split(' ', 1 );
输出:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
2.文件指针
file.seek(pin)
读取文件时先要把指针定位至文件开头,否则报错
file.tell()
将指针定位到上次读到/用到的位置,即记录指针位置
3.集合 set()
set() 有自动去重的作用,()中可以为列表/字符串/元组等
4.去重的思想:
除了用set()的方法自动去重,还可以将所有元素放到一个list中,并新建一个list,for 循环遍历所有元素,当新遍历元素不存在新list中时,就将该元素添加至新list中
5.列表功能:
list.append() 向列表中追加一个元素
list.extend()向列表中追加元素,追加的元素必须以列表的方式呈现
如:
def changeextend(str):
"print string with extend"
mylist.extend([40,50,60]);
print "print string mylist:",mylist
return
def changeappend(str):
"print string with append"
mylist.append( [7,8,9] )
print "print string mylist:",mylist
return
mylist = [10,20,30]
changeextend( mylist );
print "print extend mylist:", mylist
changeappend( mylist );
print "print append mylist:", mylist
输出:
- print string mylist: [10, 20, 30, 40, 50, 60]
- print extend mylist: [10, 20, 30, 40, 50, 60]
- print string mylist: [10, 20, 30, 40, 50, 60, [7, 8, 9]]
- print append mylist: [10, 20, 30, 40, 50, 60, [7, 8, 9]]
######################
#监控日志
#1分钟内访问次数超过200次的,就给他的ip加入黑名单
#分析:
# 1.读日志,一分钟一次
#2.获取1分钟内的所有ip
#3.判断如果ip》200写入黑名单
#4.因为每次都是从文件开头读,所以导致重复读取之前读过的,所以要记录每次读完之后的,文件指针,再用seek移动到那个位置,tell()
#ip获取方式:
# line = '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"'
# print(line.split())
# print(line.split()[0])
import time
pin = 0 #存放文件指针
while True:
with open('access.log') as fr:
ips = []
fr.seek(pin)#移动指针位置
for line in fr:
ip = line.split()[0] #取ip
ips.append(ip)
#要判断每个ip出现的次数
# for ip in set(ips):
if ips.count(ip)>200:
print('要把ip加入黑名单:%s'%ip)
pin = fr.tell()#记录已经读到了什么位置
time.sleep(60)
#字符串.split()分隔字符串,默认以空格分隔,以什么分隔就写什么,如a.split('\n')
#set()去重,但对象变为集合
#file.tell()返回文件的当前位置,即文件指针当前位置