python基于nginx访问日志统计客户端ip访问量

来源:互联网 发布:2017mac国服英雄联盟 编辑:程序博客网 时间:2024/05/22 04:42

专业的统计网站,比如百度统计,Google Analytics,cnzz等统计后台提供的都是站长常用的统计指标,比如uv,pv,在线时长,ip等,另外由于网络原因,我发现Google Analytics会比百度统计多几百的ip,所以想自己写脚本来了解下真正的访问量有多少,不过基于nginx的访问日志会比统计后台多不少,因为有不少蜘蛛的访问也会被统计进来,还有静态文件的统计,其实如果算法改进的话完全可以过滤掉那些无用的统计数据,今天给牛牛们分享下最基础的统计,另外也是为了学习和回顾python语言。

比如,服务器上有nginx的log如下:


221.221.155.54 - - [02/Aug/2014:15:16:11 +0800] "GET / HTTP/1.1" 200 8482 "http://www.zuidaima.com/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36" "-" "0.020"
221.221.155.53 - - [02/Aug/2014:15:16:11 +0800] "GET / HTTP/1.1" 200 8482 "http://www.zuidaima.com/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36" "-" "0.020"
221.221.155.54 - - [02/Aug/2014:15:16:11 +0800] "GET / HTTP/1.1" 200 8482 "http://www.zuidaima.com/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36" "-" "0.020"


统计脚本如下:

stat_ip.py

#encoding=utf8

import re

zuidaima_nginx_log_path="/usr/local/nginx/logs/www.zuidaima.com.access.log"
pattern = re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')

def stat_ip_views(log_path):
    ret={}
    f = open(log_path, "r")
    for line in f:
        match = pattern.match(line)
        if match:
            ip=match.group(0)
            if ip in ret:
                views=ret[ip]
            else:
                views=0
            views=views+1
            ret[ip]=views
    return ret
def run():
    ip_views=stat_ip_views(zuidaima_nginx_log_path)
    max_ip_view={}
    for ip in ip_views:
        views=ip_views[ip]
        if len(max_ip_view)==0:
            max_ip_view[ip]=views
        else:
            _ip=max_ip_view.keys()[0]
            _views=max_ip_view[_ip]
            if views>_views:
                max_ip_view[ip]=views
                max_ip_view.pop(_ip)

        print "ip:", ip, ",views:", views
    #总共有多少ip
    print "total:", len(ip_views)
    #最大访问的ip
    print "max_ip_view:", max_ip_view

run()

运行结果如下:

ip: 221.221.155.53 ,views: 1
ip: 221.221.155.54 ,views: 2
total: 2
max_ip_view: {'221.221.155.54': 2}

这样得到了所有ip的访问量及其最大ip的访问。

2 0
原创粉丝点击