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

相關文章
相關標籤/搜索