使用Python模块分析Nginx日志

问题:分析Nginx日志并找出访问最多10个IP地址的来源以及次数

使用Python模块IP

使用方法以及下载地址:https://pypi.python.org/pypi/17MonIP

相关python脚本:

#!/usr/bin/env python
#coding:utf8
#Auth: lad
#date:2016-12-05
#desc:parser the nginx's log,the head of 10
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
 
import IP
import os
 
cnt=10
 
fd = open("/tmp/IP.txt","w")
ipStr = os.popen("cat /tmp/access.log|awk '{print $6}'|sort | uniq -c | sort -nr | head -10 ")
 
fd.write(ipStr.read())
fd.close()
 
fd1 = open("/tmp/IP.txt","r")
fd2 = open("/tmp/nginx_IP.txt","w+")
for i in range(1,cnt+1):
    d = fd1.readline()
    print >> fd2,"访问次数:%8s 访问IP:%16s IP地址来源:%20s"%(d.split()[0],d.split()[1],IP.find(d.split()[1]))
fd1.close()
fd2.close()
print "OK"

具体使用awk分割的时候需要考虑自己日志的格式,根据格式切割。

执行结果:

使用Python模块分析Nginx日志

下面关于Nginx的文章您也可能喜欢,不妨参考下:

Nginx 的详细介绍请点这里
Nginx 的下载地址请点这里

猜你喜欢

转载自www.linuxidc.com/Linux/2017-02/140361.htm