nginx的访问日志位置:'/home/nginx/logs/access.log'
import re
def count_patt(fname, patt):
cpatt = re.compile(patt)
result = {}
with open(fname) as fobj:
for IP in fobj:
m = cpatt.search(IP)
if m:
key = m.group()
result[key] = result.get(key, 0) + 1 #第一次字典为空,get方法设置没找到"IP"返回"0"(默认返回查不到返回None),第二次找到IP,自加1
return result
if __name__ == '__main__':
fname = '/home/nginx/logs/access.log'
# fname = '/home/nginx/logs/error.log'
ip = '^(\d+\.){3}\d+' # 日志开头的ip地址
print(count_patt(fname, ip))