用Python统计nginx日志中IP访问次数


在逛大牛的blog时发现的代码,然后就转过来了`(*∩_∩*)′,我自己一般是用awk进行统计的(并且用到了之前搜集到的一个纯真IP地址库的Python解析代码进行了地理位置的统计,大概就是:访问次数、IP地址、地理位置信息,如:“578 111.206.61.180 北京市/联通”),这里用的是Python,学到了如何用Python进行去重(思想就是:将IP地址存为数组下标进行去重以及计数,然后将IP地址和访问次数作为字典中的键值对)以及排序,代码如下:

#!/usr/bin/env python
# coding=utf-8

import sys

class Log:
    def __init__(self, filename, dic, count):
        self.filename = filename
        self.dic = dic
        self.count = count

    def parse(self):
        i = 1
        f = file(self.filename)
        while True:
            line = f.readline()
            if len(line)==0:
                break
            ip = line.split(' ')
            if ip[0] in dic:
                self.dic[ip[0]] = self.dic[ip[0]]+1
            else:
                self.dic[ip[0]] = i
        soredic = sorted(self.dic.items(), key=lambda d:d[1], reverse=True)
        counts = 0;
        for item in soredic:
            if counts==int(self.count):
                break
            print("IP: %stTotal Times: %s"%(item[0], item[1]))
            counts = counts+1
        f.close()

if __name__=="__main__":
    if len(sys.argv)<3:
        print('ntUsage: python parseLog.py /path/to/access.log topXntExample: python parseLog.py /path/to/access.log 20')
        sys.exit()
    dic={}
    log=Log(sys.argv[1], dic, sys.argv[2])
    log.parse()

效果也不错,都可以直接和之前的解析IP地址的Python代码进行整合了。

然后想多说的一句就是,之前介绍过的ngxtop那个工具就是用Python写的,功能和效果比较给力,大家可以试试:ngxtop:在命令行实时监控 Nginx 的神器

 

原文地址:

http://www.iswin.org/a/14

,

《“用Python统计nginx日志中IP访问次数”》 有 5 条评论

  1. 去重计数的通用方法:

    def count_if(my_list):
    counts = {}
    for item in my_list:
    if item not in counts:
    counts[item] = 0
    counts[item] += 1
    return counts

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注