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基础教程之lambda表达式使用方法
Feb 12 Python
使用Python进行新浪微博的mid和url互相转换实例(10进制和62进制互算)
Apr 25 Python
使用python编写批量卸载手机中安装的android应用脚本
Jul 21 Python
Python基于递归算法实现的汉诺塔与Fibonacci数列示例
Apr 18 Python
Python爬虫常用小技巧之设置代理IP
Sep 13 Python
解决python 上传图片限制格式问题
Oct 30 Python
python 监测内存和cpu的使用率实例
Nov 28 Python
python 实现方阵的对角线遍历示例
Nov 29 Python
Python class的继承方法代码实例
Feb 14 Python
python实时监控logstash日志代码
Apr 27 Python
Python类绑定方法及非绑定方法实例解析
Oct 09 Python
Python实现仓库管理系统
May 30 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数组内存耗用太多问题的解决方法
2010/04/05 PHP
PHP 处理TXT文件(打开/关闭/检查/读取)
2013/05/13 PHP
PHP判断网络文件是否存在的方法
2015/03/12 PHP
document 和 document.all 分别什么时候用
2006/06/22 Javascript
jQuery 注意事项 与原因分析
2009/04/24 Javascript
html 锁定页面(js遮罩层弹出div效果)
2009/10/27 Javascript
JS实现QQ图片一闪一闪的效果小例子
2013/07/31 Javascript
IE8下String的Trim()方法失效的解决方法
2013/11/08 Javascript
Node.js中AES加密和其它语言不一致问题解决办法
2014/03/10 Javascript
JavaScript控制网页平滑滚动到指定元素位置的方法
2015/04/17 Javascript
推荐10 个很棒的 jQuery 特效代码
2015/10/04 Javascript
sencha ext js 6 快速入门(必看)
2016/06/01 Javascript
bootstrap导航、选项卡实现代码
2016/12/28 Javascript
javascript数据结构中栈的应用之符号平衡问题
2017/04/11 Javascript
文本溢出插件jquery.dotdotdot.js使用方法详解
2017/06/22 jQuery
Vue基于NUXT的SSR详解
2017/10/24 Javascript
原生JavaScript实现换肤
2021/02/19 Javascript
python根据给定文件返回文件名和扩展名的方法
2015/03/27 Python
python简单实现旋转图片的方法
2015/05/30 Python
使用python将多个excel文件合并到同一个文件的方法
2019/07/09 Python
Python列表(list)所有元素的同一操作解析
2019/08/01 Python
python/Matplotlib绘制复变函数图像教程
2019/11/21 Python
采用冷却技术的超自然舒适度:GhostBed床垫
2018/09/18 全球购物
马来西亚最大的在线隐形眼镜商店:MrLens
2019/03/27 全球购物
幼儿园家长会邀请函
2014/01/15 职场文书
致长跑运动员广播稿
2014/01/31 职场文书
创先争优承诺书范文
2014/03/31 职场文书
市场部经理岗位职责
2014/04/10 职场文书
婚前协议书怎么写
2014/04/15 职场文书
我的梦想演讲稿
2014/04/30 职场文书
文秘专业应届生求职信
2014/05/26 职场文书
ktv服务员岗位职责
2015/02/09 职场文书
同学会演讲稿
2019/04/02 职场文书
创业分两种人:那么哪些适合创业?,哪些适合不适合创业呢?
2019/08/23 职场文书
详解在OpenCV中如何使用图像像素
2022/03/03 Python
Redis高可用集群redis-cluster详解
2022/03/20 Redis