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中pycurl库的用法实例
Sep 30 Python
Python基于回溯法子集树模板解决最佳作业调度问题示例
Sep 08 Python
Python数据结构与算法之链表定义与用法实例详解【单链表、循环链表】
Sep 28 Python
Python算法之图的遍历
Nov 16 Python
Python数据结构与算法之图的最短路径(Dijkstra算法)完整实例
Dec 12 Python
Python实现爬取百度贴吧帖子所有楼层图片的爬虫示例
Apr 26 Python
python3 cvs将数据读取为字典的方法
Dec 22 Python
python实现二维数组的对角线遍历
Mar 02 Python
详解Python 函数如何重载?
Apr 23 Python
解决python有时候import不了当前的包问题
Aug 28 Python
Python用摘要算法生成token及检验token的示例代码
Dec 01 Python
Autopep8的使用(python自动编排工具)
Mar 02 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分页时出现的Fatal error的解决方法
2011/04/18 PHP
php自定义时间转换函数示例
2016/12/07 PHP
PHP+Ajax实现上传文件进度条动态显示进度功能
2018/06/04 PHP
jQuery 行背景颜色的交替显示(隔行变色)实现代码
2009/12/13 Javascript
js null undefined 空区别说明
2010/06/13 Javascript
写js时遇到的一些小问题
2010/12/06 Javascript
JS方法调用括号的问题探讨
2014/01/24 Javascript
Jquery中find与each方法用法实例
2015/02/04 Javascript
JavaScript中的Math.E属性使用详解
2015/06/12 Javascript
jquery编写Tab选项卡滚动导航切换特效
2020/07/17 Javascript
JS简单测试循环运行时间的方法
2016/09/04 Javascript
如何给ss bash 写一个 WEB 端查看流量的页面
2017/03/23 Javascript
Node学习记录之cluster模块
2017/05/31 Javascript
使用vue构建多页面应用的示例
2020/10/22 Javascript
Python引用类型和值类型的区别与使用解析
2017/10/17 Python
Python高级用法总结
2018/05/26 Python
python实现多人聊天室
2020/03/31 Python
利用ctypes获取numpy数组的指针方法
2019/02/12 Python
Win10下python 2.7与python 3.7双环境安装教程图解
2019/10/12 Python
pycharm运行scrapy过程图解
2019/11/22 Python
python实现飞行棋游戏
2020/02/05 Python
Python响应对象text属性乱码解决方案
2020/03/31 Python
Python Celery异步任务队列使用方法解析
2020/08/10 Python
6PM官网:折扣鞋、服装及配饰
2018/08/03 全球购物
linux面试题参考答案(3)
2012/09/13 面试题
AJAX都有哪些有点和缺点
2012/11/03 面试题
中专毕业自我鉴定
2013/10/16 职场文书
大学自我鉴定
2013/12/20 职场文书
美丽乡村建设实施方案
2014/03/23 职场文书
简易离婚协议书范本
2014/10/24 职场文书
收银员岗位职责范本
2015/04/07 职场文书
2019广播稿怎么写
2019/04/17 职场文书
2019学校请假条格式及范文
2019/06/25 职场文书
导游词之江西赣州
2019/10/15 职场文书
python实现ROA算子边缘检测算法
2021/04/05 Python
Python中使用Opencv开发停车位计数器功能
2022/04/04 Python