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

前言:python统计apache、nginx访问日志IP访问次数而且排序(显示前20条)。其实用awk+sort等命令能够实现,用awk数组也能够实现,这里只是用python尝试下。
html

 

apache脚本:python

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脚本:linux

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))

 

转自nginx

python统计apache、nginx访问日志IP访问次数而且排序(显示前20条)-赛里-51CTO博客
https://blog.51cto.com/net881004/2134826apache

其余参考数组

Python基于nginx访问日志并统计IP访问量 - 88686 - 博客园 https://www.cnblogs.com/www886/p/4341313.html
python获取nginx超时访问日志 - 独孤仁的专栏 - CSDN博客 https://blog.csdn.net/kong2030/article/details/81181057
Python分析NGINX日志里面相同IP第一次访问时间和最后一次访问时间-GoDevops-51CTO博客 https://blog.51cto.com/dreamlinux/2120866
Python3 max() 函数详解 获取多个参数或列表中的最大值 - 张恺阳博客 https://www.zky.name/article/51.html

app

相关文章
相关标签/搜索