`
desert3
  • 浏览: 2139673 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
社区版块
存档分类
最新评论

用python分析nginx的access日志

阅读更多
项目正式发布后,有需求要分析下nginx的access日志内容,于是写了如下脚本:

#! /usr/bin/env python 
# -*- coding: utf-8 -*- 
#@author zcwang3@gmail.com
#@version 2011-04-12 16:34
#Nginx日志分析,初始做成 

import os
import fileinput
import re

#日志的位置
dir_log  = r"D:\python cmd\nginxlog"

#使用的nginx默认日志格式$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"'
#日志分析正则表达式

#203.208.60.230 
ipP = r"?P<ip>[\d.]*";

#[21/Jan/2011:15:04:41 +0800]
timeP = r"""?P<time>\[           #以[开始
            [^\[\]]* #除[]以外的任意字符  防止匹配上下个[]项目(也可以使用非贪婪匹配*?)  不在中括号里的.可以匹配换行外的任意字符  *这样地重复是"贪婪的“ 表达式引擎会试着重复尽可能多的次数。
            \]           #以]结束
        """

#"GET /EntpShop.do?method=view&shop_id=391796 HTTP/1.1"
requestP = r"""?P<request>\"          #以"开始
            [^\"]* #除双引号以外的任意字符 防止匹配上下个""项目(也可以使用非贪婪匹配*?)
            \"          #以"结束
            """

statusP = r"?P<status>\d+"

bodyBytesSentP = r"?P<bodyByteSent>\d+"

#"http://test.myweb.com/myAction.do?method=view&mod_id=&id=1346"
referP = r"""?P<refer>\"          #以"开始
            [^\"]* #除双引号以外的任意字符 防止匹配上下个""项目(也可以使用非贪婪匹配*?)
            \"          #以"结束
        """

#"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"'
userAgentP = r"""?P<userAgent>\"              #以"开始
        [^\"]* #除双引号以外的任意字符 防止匹配上下个""项目(也可以使用非贪婪匹配*?)
        \"              #以"结束
            """

#原理:主要通过空格和-来区分各不同项目,各项目内部写各自的匹配表达式
nginxLogPattern = re.compile(r"(%s)\ -\ -\ (%s)\ (%s)\ (%s)\ (%s)\ (%s)\ (%s)" %(ipP, timeP, requestP, statusP, bodyBytesSentP, referP, userAgentP), re.VERBOSE)

def processDir(dir_proc):
    for file in os.listdir(dir_proc):
        if os.path.isdir(os.path.join(dir_proc, file)):
            print "WARN:%s is a directory" %(file)
            processDir(os.path.join(dir_proc, file))
            continue

        if not file.endswith(".log"):
            print "WARN:%s is not a log file" %(file)
            continue

        print "INFO:process file %s" %(file)
        for line in fileinput.input(os.path.join(dir_proc, file)):
            matchs = nginxLogPattern.match(line)
            if matchs!=None:
                allGroups = matchs.groups()
                ip = allGroups[0]
                time = allGroups[1]
                request = allGroups[2]
                status =  allGroups[3]
                bodyBytesSent = allGroups[4]
                refer = allGroups[5]
#                userAgent = allGroups[6]
                userAgent = matchs.group("userAgent")
                print userAgent
                
                #统计HTTP状态码的数量
                GetResponseStatusCount(userAgent)
                #在这里补充其他任何需要的分析代码
            else:
                raise Exception
                
        fileinput.close()

allStatusDict = {}
#统计HTTP状态码的数量
def GetResponseStatusCount(status):
    if allStatusDict.has_key(status):
        allStatusDict[status] += 1;
    else:
        allStatusDict[status] = 1;
    
        
if __name__ == "__main__":
    processDir(dir_log)
    print allStatusDict
    #根据值进行排序(倒序)
    print sorted(allStatusDict.items(), key=lambda d:d[1], reverse=True)
    print "done, python is great!"


得到的HTTP状态码的数量如下:
{'200': 287559, '302': 6743, '304': 4074, '404': 152918, '499': 887, '400': 14, '504': 93, '502': 300, '503': 5, '500': 88353}


各IP访问网站的次数如下(前10的IP):
[('220.178.14.98', 323230), ('220.181.94.225', 120870), ('203.208.60.230', 14342), ('61.135.249.220', 6479), ('203.208.60.88', 5426), ('61.135.249.216', 4867), ('123.125.71.94', 1290), ('123.125.71.104', 1282), ('123.125.71.108', 1280), ('123.125.71.110', 1278),  余下不显示]

从原始信息中提取IP后可以做一些额外的分析工作:如访问量前10的IP等 数据量大时采用hashIp后取模再统计
0
0
分享到:
评论
1 楼 dacoolbaby 2016-10-31  
非常棒的正则表达式,非常适用。
万分感谢。

相关推荐

    Python 分析Nginx访问日志并保存到MySQL数据库实例

    使用Python 分析Nginx access 日志,根据Nginx日志格式进行分割并存入MySQL数据库。一、Nginx access日志格式如下:复制代码 代码如下:$remote_addr – $remote_user [$time_local] “$request” $status $body_...

    python实现的分析并统计nginx日志数据功能示例

    本文实例讲述了python实现的分析并统计nginx日志数据功能。分享给大家供大家参考,具体如下: 利用python脚本分析nginx日志内容,默认统计ip、访问url、状态,可以通过修改脚本统计分析其他字段。 一、脚本运行方式 ...

    python实现分析apache和nginx日志文件并输出访客ip列表的方法

    这里使用python分析apache和nginx日志文件输出访客ip列表 ips = {} fh = open("/var/log/nginx/access.log", "r").readlines() for line in fh: ip = line.split(" ")[0] if 6 &lt; len(ip) &lt;=15: ips[ip] = ...

    浅析python 定时拆分备份 nginx 日志的方法

     python nginx_logs_splter.py –nginxConf=nginx.conf –nginxDir=xxxxx –logPrefixs=access,error 2.在定时任务中加一个定时任务,调用这个 bat 文件;  2.1 开始-程序-管理工具-任务计划程序;   2.2 ...

    日志记录:分析您的NGINX访问日志并为人们访问您的服务的位置创建精美的地图

    分析您的NGINX访问日志并为人们访问您的服务的位置创建精美的地图。 如何使用 首先,请确保您已安装python3.x和geolite2 。 可以使用pip install maxminddb-geolite2 python-geoip-geolite2通过pip pip install ...

    access_qx.log

    数据分析实战-利用pandas对nginx...本次实验以数据小站-数据科学成长之路的某个时间段的nginx访问日志为示例,抽取大概一万条的日志访问记录,通过python中的pandas库,对日志进行挖掘分析,进行一个数据应用实战项目。

    log2json:将日志文件转换为json或文本格式

    log2json /var/log/nginx/access.log -o $HOME /nginx-access.txt 将多个日志文件转换为带有目标目录的文本 log2json /var/log/nginx/access.log /var/log/nginx/error.log -d $HOME /log2json/ 如果未提供目标...

    窥视:快速统计一下nginx如何处理请求

    python3 peek.py /var/log/nginx/access.log 根据需要调整/path/to/access.log。 为了保持统计数据的持久性,请添加--persist标志 python3 peek.py /var/log/nginx/access.log --persist 当前,这会将统计信息保存...

    采用ngxtop实现nginx实时访问数据统计

    ngxtop 允许你对 NGINX 的访问日志 (access log) 进行实时解析, 并输出类似 top 的有用信息。 ngxtop 是 python 脚本安装包,需要python支持。 对于python的包和库文件我们一般喜欢pip管理,没有安装的可以: wget...

    Django在Ubuntu14.04的部署方法

    第一步。 sudo apt-get update sudo apt-get upgrade 先更新。。 Django的主流部署方式:nginx+uwsgi+django ...3.日志:/var/log/nginx/access.log – error.log 第三步,安装uwsgi sudo apt-get install python3-

    lofka:一款性能高,兼容性好,输出优美的日志收集管理系统

    tail -f /var/log/nginx/access.log|grep xxxxxFUCKxxxx日志输出多了看不到关键点,输出等级高了看不到系列?多个服务器的日志是否看起来很痛苦?常常使用TMUX开多个小窗口排查问题在哪里,眼睛都看不过来。快试试 ...

    ballcone:Ballcone是一种快速,轻量级的服务器端Web分析解决方案

    球锥 Ballcone是一种快速,轻量级的服务器端Web分析解决方案。 您的网站上不需要JavaScript。 屏幕截图 ...Ballcone会捕获nginx通过捆绑的( 65140/udp )以JSON格式导出的access_log条目。 这些条目存储在

Global site tag (gtag.js) - Google Analytics