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


Posted in Python onMarch 13, 2014

使用Python 分析Nginx access 日志,根据Nginx日志格式进行分割并存入MySQL数据库。
一、Nginx access日志格式如下:

$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"' #使用的是nginx默认日志格式

二、Nginx access 日志内容如下:
182.19.31.129 - - [2013-08-13T00:00:01-07:00] "GET /css/anniversary.css HTTP/1.1" 304 0 "http://www.chlinux.net/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36" "-"

三、下面是Python 分析nginx日志的Python代码:
#!/usr/bin/env python
#coding:utf8
import os
import fileinput
import re
import sys
import MySQLdb
#日志的位置
logfile=open("access_20130812.log")
#使用的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"
#"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>\"[^\"]*\""""
#以(开始, 除双引号以外的任意字符 防止匹配上下个()项目(也可以使用非贪婪匹配*?),以"结束
#(compatible; Googlebot/2.1; +http://www.google.com/bot.html)"'
userSystems = re.compile(r'\([^\(\)]*\)')
#以"开始,除双引号以外的任意字符防止匹配上下个""项目(也可以使用非贪婪匹配*?),以"结束
userlius = re.compile(r'[^\)]*\"')
#原理:主要通过空格和-来区分各不同项目,各项目内部写各自的匹配表达式
nginxLogPattern = re.compile(r"(%s)\ -\ -\ (%s)\ (%s)\ (%s)\ (%s)\ (%s)\ (%s)" %(ipP, timeP, requestP, statusP, bodyBytesSentP, referP, userAgentP), re.VERBOSE)
#数据库连接信息
conn=MySQLdb.connect(host='192.168.1.22',user='test',passwd='pass',port=3306,db='python')
cur=conn.cursor()
sql = "INSERT INTO python.test VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)"
while True:
    line = logfile.readline()
    if not line:break
    matchs = nginxLogPattern.match(line)
    if matchs != None:
        allGroup = matchs.groups()
        ip = allGroup[0]
        time = allGroup[1]
        request = allGroup[2]
        status = allGroup[3]
        bodyBytesSent = allGroup[4]
        refer = allGroup[5]
        userAgent = allGroup[6]
        Time = time.replace('T',' ')[1:-7]
        if len(userAgent) > 20:
            userinfo = userAgent.split(' ')
            userkel =  userinfo[0]
            try:
                usersystem = userSystems.findall(userAgent)
                usersystem = usersystem[0]
                print usersystem
                userliu = userlius.findall(userAgent)
                value = [ip,Time,request,status,bodyBytesSent,refer,userkel,usersystem,userliu[1]]
                conn.commit()
                print value
            except IndexError:
                userinfo = userAgent
                value = [ip,Time,request,status,bodyBytesSent,refer,userinfo,"",""]
        else:
            useraa = userAgent
            value = [ip,Time,request,status,bodyBytesSent,refer,useraa,"",""]
    try:
        result = cur.execute(sql,value)
        #conn.commit()
        print result
    except MySQLdb.Error,e:
        print "Mysql Error %d: %s" % (e.args[0], e.args[1])
conn.commit()
conn.close()

四、存入数据库后数据是如下图:

Python 相关文章推荐
python采用getopt解析命令行输入参数实例
Sep 30 Python
Python 对象中的数据类型
May 13 Python
TensorFlow实现简单卷积神经网络
May 24 Python
python检测文件夹变化,并拷贝有更新的文件到对应目录的方法
Oct 17 Python
python实现扫描局域网指定网段ip的方法
Apr 16 Python
基于Python的OCR实现示例
Apr 03 Python
使用Django清空数据库并重新生成
Apr 03 Python
Python colormap库的安装和使用详情
Oct 06 Python
python3实现名片管理系统(控制台版)
Nov 29 Python
Django数据模型中on_delete使用详解
Nov 30 Python
bat批处理之字符串操作的实现
Mar 16 Python
Python实现抖音热搜定时爬取功能
Mar 16 Python
详解Python中的__init__和__new__
Mar 12 #Python
python文件和目录操作方法大全(含实例)
Mar 12 #Python
Python 文件读写操作实例详解
Mar 12 #Python
Python 异常处理实例详解
Mar 12 #Python
Python break语句详解
Mar 11 #Python
Python continue语句用法实例
Mar 11 #Python
Python pass 语句使用示例
Mar 11 #Python
You might like
php 文件上传代码(限制jpg文件)
2010/01/05 PHP
PHP生成二维码的两个方法和实例
2014/07/01 PHP
php成功操作redis cluster集群的实例教程
2019/01/13 PHP
PHP扩展类型及安装方式解析
2020/04/27 PHP
一个原生的用户等级的进度条
2010/07/03 Javascript
鼠标事件延时切换插件
2011/03/12 Javascript
如何使用Javascript获取距今n天前的日期
2013/07/08 Javascript
使用ImageMagick进行图片缩放、合成与裁剪(js+python)
2013/09/16 Javascript
js写的评论分页(还不错)
2013/12/23 Javascript
jquery的each方法使用示例分享
2014/03/25 Javascript
PHP配置文件php.ini中打开错误报告的设置方法
2015/01/09 PHP
JavaScript中的this到底是什么(一)
2015/12/09 Javascript
jQuery使用$.ajax进行即时验证实例详解
2015/12/11 Javascript
Javascript基础回顾之(二) js作用域
2017/01/31 Javascript
Bootstrap与Angularjs的模态框实例代码
2017/08/03 Javascript
angularjs实现猜大小功能
2017/10/23 Javascript
详解ajax的data参数错误导致页面崩溃
2018/04/30 Javascript
在微信小程序中使用vant的方法
2019/06/07 Javascript
Python中标准库OS的常用方法总结大全
2017/07/19 Python
python遍历文件夹下所有excel文件
2018/01/03 Python
Windows上使用Python增加或删除权限的方法
2018/04/24 Python
python爬虫之urllib3的使用示例
2018/07/09 Python
解决Python 中英文混输格式对齐的问题
2018/07/16 Python
python 自动重连wifi windows的方法
2018/12/18 Python
python基于itchat模块实现微信防撤回
2019/04/29 Python
Python基础学习之函数方法实例详解
2019/06/18 Python
详解利用python+opencv识别图片中的圆形(霍夫变换)
2019/07/01 Python
如何分离django中的媒体、静态文件和网页
2019/11/12 Python
python新手学习使用库
2020/06/11 Python
html5使用canvas压缩图片的示例代码
2018/09/11 HTML / CSS
竟聘演讲稿范文
2013/12/31 职场文书
适用于所有创业者的创业计划书
2014/02/05 职场文书
会计电算化毕业生自荐信
2014/03/03 职场文书
教师自我剖析材料(四风问题)
2014/09/30 职场文书
推荐信范文大全
2015/03/27 职场文书
Python通过m3u8文件下载合并ts视频的操作
2021/04/16 Python