首页 > 编程语言 > 详细

python统计apache、nginx访问日志IP访问次数并且排序(显示前20条)

时间:2018-07-02 00:02:13      阅读:392      评论:0      收藏:0      [点我收藏+]
前言:python统计apache、nginx访问日志IP访问次数并且排序(显示前20条)。其实用awk+sort等命令可以实现,用awk数组也可以实现,这里只是用python尝试下。


apache脚本:

ips = {}
with open("/root/mail_access_log-20180629") as fh:
    for line in fh:
        ip = line.split(" ")[0]
        if 6 < len(ip) <=15:
            ips[ip] = ips.get(ip, 0) + 1

ip_num = []
for ipaddr,num in ips.items():
   ip_num.append((ipaddr,num))

ip_num.sort(key=lambda x: x[1], reverse=True)

for ipaddr,num in ip_num[:20]:
    print('IP地址为{}, 访问次数为{}'.format(ipaddr,num))



nginx脚本:

ips = {}
with open("/root/access.log-20180629") as fh:
    for line in fh:
        ip = line.split(" ")[0]
        if 6 < len(ip) <=15:
            ips[ip] = ips.get(ip, 0) + 1

ip_num = []
for ipaddr,num in ips.items():
   ip_num.append((ipaddr,num))

ip_num.sort(key=lambda x: x[1], reverse=True)

for ipaddr,num in ip_num[:20]:
    print('IP地址为{}, 访问次数为{}'.format(ipaddr,num))


python统计apache、nginx访问日志IP访问次数并且排序(显示前20条)

原文:http://blog.51cto.com/net881004/2134826

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!