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的urllib和urllib2模块制作爬虫的实例教程
Jan 20 Python
Python的时间模块datetime详解
Apr 17 Python
python实现各进制转换的总结大全
Jun 18 Python
关于python多重赋值的小问题
Apr 17 Python
PyQT5 QTableView显示绑定数据的实例详解
Jun 25 Python
Django Rest framework权限的详细用法
Jul 25 Python
python基于event实现线程间通信控制
Jan 13 Python
python 6.7 编写printTable()函数表格打印(完整代码)
Mar 25 Python
python中如何进行连乘计算
May 28 Python
基于tensorflow for循环 while循环案例
Jun 30 Python
详解numpy1.19.4与python3.9版本冲突解决
Dec 15 Python
Python find()、rfind()方法及作用
Dec 24 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&amp;java(一)
2006/10/09 PHP
php单例模式实现方法分析
2015/03/14 PHP
PHP微信开发之查询微信精选文章
2016/06/23 PHP
php实现文件与16进制相互转换的方法示例
2017/02/16 PHP
原生javaScript实现图片延时加载的方法
2014/12/22 Javascript
jQuery实现为图片添加镜头放大效果的方法
2015/06/25 Javascript
基于AngularJS实现页面滚动到底自动加载数据的功能
2015/10/16 Javascript
mvc 、bootstrap 结合分布式图简单实现分页
2016/10/10 Javascript
使用Node.js搭建静态资源服务详细教程
2017/08/02 Javascript
vue中element组件样式修改无效的解决方法
2018/02/03 Javascript
JavaScript获取某一天所在的星期
2019/09/05 Javascript
JS实现无限轮播无倒退效果
2020/09/21 Javascript
[01:36:19]Secret vs NB 2018国际邀请赛小组赛BO2 第一场 8.19
2018/08/21 DOTA
python使用reportlab画图示例(含中文汉字)
2013/12/03 Python
Python logging模块学习笔记
2014/05/24 Python
Python实现把数字转换成中文
2015/06/29 Python
详解K-means算法在Python中的实现
2017/12/05 Python
win7 x64系统中安装Scrapy的方法
2018/11/18 Python
python中ImageTk.PhotoImage()不显示图片却不报错问题解决
2018/12/06 Python
Python实现多态、协议和鸭子类型的代码详解
2019/05/05 Python
python lxml中etree的简单应用
2019/05/10 Python
Python 使用folium绘制leaflet地图的实现方法
2019/07/05 Python
pandas 选取行和列数据的方法详解
2019/08/08 Python
10行Python代码计算汽车数量的实现方法
2019/10/23 Python
python文件和文件夹复制函数
2020/02/07 Python
python属于软件吗
2020/06/18 Python
python从Oracle读取数据生成图表
2020/10/14 Python
如何在pycharm中安装第三方包
2020/10/27 Python
Dockers美国官方网站:卡其裤、男士服装、鞋及配件
2016/11/22 全球购物
仓库组长岗位职责
2014/01/29 职场文书
瘦西湖导游词
2015/02/03 职场文书
迎新晚会主持词开场白
2015/05/28 职场文书
消费者理赔投诉书
2015/07/02 职场文书
污染环境建议书
2015/09/14 职场文书
2019员工保密协议书(3篇)
2019/09/23 职场文书
idea编译器vue缩进报错问题场景分析
2021/07/04 Vue.js