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

前言: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条)-赛里-51CTO博客
https://blog.51cto.com/net881004/2134826

其他参考

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

posted @   paul_hch  阅读(624)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2017-05-31 linux下如何添加一个用户并且让用户获得root权限
2017-05-31 vim加密文件
点击右上角即可分享
微信分享提示