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实现国外赌场热门游戏Craps(双骰子)
Mar 31 Python
python 简单备份文件脚本v1.0的实例
Nov 06 Python
django admin添加数据自动记录user到表中的实现方法
Jan 05 Python
python中in在list和dict中查找效率的对比分析
May 04 Python
Python绘制的二项分布概率图示例
Aug 22 Python
在Python中实现替换字符串中的子串的示例
Oct 31 Python
详解基于python-django框架的支付宝支付案例
Sep 23 Python
使用Tensorboard工具查看Loss损失率
Feb 15 Python
Python接口测试get请求过程详解
Feb 28 Python
为什么说python适合写爬虫
Jun 11 Python
自学python用什么系统好
Jun 23 Python
基于Python实现射击小游戏的制作
Apr 06 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 第一节 php简介
2012/04/28 PHP
php断点续传之如何分割合并文件
2014/03/22 PHP
PHP集成百度Ueditor 1.4.3
2014/11/23 PHP
php生成rss类用法实例
2015/04/14 PHP
php+mysql实现无限级分类
2015/11/11 PHP
PHP的全局错误处理详解
2016/04/25 PHP
jquery实现居中弹出层代码
2010/08/25 Javascript
分享一个我自己写的ToolTip提示插件(附源码)
2013/01/20 Javascript
CheckBoxList多选样式jquery、C#获取选择项
2013/09/06 Javascript
jquery删除ID为sNews的tr元素的内容
2014/04/10 Javascript
判断iframe里的页面是否加载完成
2014/06/06 Javascript
javascript返回顶部的按钮实现方法
2016/01/09 Javascript
JS/jQuery判断DOM节点是否存在的简单方法
2016/11/24 Javascript
ES6正则的扩展实例详解
2017/04/25 Javascript
jQuery Tree Multiselect使用详解
2017/05/02 jQuery
使用prop解决一个checkbox选中后再次选中失效的问题
2017/07/05 Javascript
浅谈Angular4中常用管道
2017/09/27 Javascript
JS随机排序数组实现方法分析
2017/10/11 Javascript
20行JS代码实现粘贴板复制功能
2018/02/06 Javascript
浅谈PDF.js使用心得
2018/06/07 Javascript
vue3.0 CLI - 3.2 路由的初级使用教程
2018/09/20 Javascript
vue遍历生成的输入框 绑定及修改值示例
2019/10/30 Javascript
跟老齐学Python之用while来循环
2014/10/02 Python
在Django框架中伪造捕捉到的URLconf值的方法
2015/07/18 Python
Python实现字符型图片验证码识别完整过程详解
2019/05/10 Python
django连接oracle时setting 配置方法
2019/08/29 Python
浅谈matplotlib 绘制梯度下降求解过程
2020/07/12 Python
中国汽车租赁行业头部企业:一嗨租车
2019/05/16 全球购物
英国男女豪华配饰和礼品网站:Black.co.uk
2020/02/28 全球购物
编辑找工作求职信范文
2013/12/16 职场文书
后备干部培训方案
2014/05/22 职场文书
超市创意活动方案
2014/08/15 职场文书
幼儿园老师新年寄语2015
2014/12/08 职场文书
留学推荐信中文范文
2015/03/26 职场文书
党小组评议意见
2015/06/02 职场文书
磁贴还没死, 微软Win11可修改注册表找回Win10开始菜单
2021/11/21 数码科技