python脚本统计日志独立ip
题目:
有如下log文件,请打印出独立IP,并统计独立IP数,打印出访问最多的前5个ip及访问次数:
log文件www.log内容类似如下格式:
125.78.48.67 - - [25/Dec/2014:15:31:20 +0800] "GET /loGo.jpg Http/1.1" 200 5183 "-" "Mozilla/5.0 (compatible; MSIE 9.0; windows NT 6.1; Trident/5.0)"
101.226.166.226 - - [25/Dec/2014:15:31:21 +0800] "GET " 302 26 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWEBKit/537.1 (Khtml, like Gecko) Chrome/21.0.1180.89 Safari/537.1; 360Spider"
101.226.166.226 - - [25/Dec/2014:15:31:21 +0800] "GET " "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1; 360Spider"
125.78.48.67 - - [25/Dec/2014:15:31:20 +0800] "GET /topbanner.jpg HTTP/1.1" 200 51794 "-" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
118.192.170.7 - - [25/Dec/2014:15:31:09 +0800] "GET HTTP/1.1" 200 34381 "-" "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36 SE 2.X MetaSr 1.0"
118.192.170.7 - - [25/Dec/2014:15:31:22 +0800] "GET HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36 SE 2.X MetaSr 1.0"
解题思路:
1,读取log内容,过滤出ip地址,保存到一个列表a中
2,将列表a去重获得列表b
3,以b列表长度为最大循环次数做循环获得列表a1,将a1的值添加到b1,然后重置a1
4,将b1进行反向排序,打印出来
5,让使用者选择输出访问最多的前几个ip,也可以给函数传递参数,给一个默认参数打印前几个
--- 刚学python,写的很烂,code:
#!/usr/bin/env Python
import re
re1 = r'^\d+\.\d+\.\d+\.\d+'
reg = re.compile(re1)
fp = open('www.log')
f_content = fp.readlines()
fp.close()
a = []
for lines in f_content:
ip = re.findall(reg,lines)
a.append(ip[0])
b = list(set(a))
b1 = []
for i in range(len(b)):
a1 = []
a1.append(a.count(b[i]))
a1.append(b[i])
b1.append(a1)
b1.sort(reverse=True)
k = 1
for j in b1:
print j[0],j[1]
if k == 5:
break
k += 1
--- shell 只需一条命令:
awk '{print $1}' www.log |sort|uniq -c|sort -nr|head -n5
--- 改良了下python代码:
#!/usr/bin/env python
#coding:utf-8
import re
import sys
def getIP():
log = raw_input('请输入要查询的日志文件名,包括扩展名:')
re1 = r'^\d+\.\d+\.\d+\.\d+'
reg = re.compile(re1)
fp = open(log)
f_content = fp.readlines()
fp.close()
a = []
for lines in f_content:
ip = re.findall(reg,lines)
a.append(ip[0])
b = list(set(a))
b1 = []
for i in range(len(b)):
a1 = []
a1.append(a.count(b[i]))
a1.append(b[i])
b1.append(a1)
b1.sort(reverse=True)
k = 1
num = raw_input('请输入一个数字要查询前几个ip:')
num = int(num)
for j in b1:
print j[0],j[1]
if k == num:
break
k += 1
if __name__ == '__main__':
getIP()
--- 取消了re正则匹配的麻烦:
#!/usr/bin/env python
#coding:utf-8
def getIP():
log = raw_input('请输入要查询的日志文件名,包括扩展名:')
fp = open(log)
f_lines = fp.readlines()
fp.close()
ips = []
for line in f_lines:
ip = line.split()[0]
ips.append(ip)
b = list(set(ips))
b1 = []
for i in range(len(b)):
a1 = []
a1.append(ips.count(b[i]))
a1.append(b[i])
b1.append(a1)
b1.sort(reverse=True)
k = 1
num = raw_input('请输入一个数字要查询前几个ip:')
num = int(num)
for j in b1:
print j[0],j[1]
if k == num:
break
k += 1
if __name__ == '__main__':
getIP()
相关文章