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读取word文档的方法
May 09 Python
python引用DLL文件的方法
May 11 Python
浅谈Python在pycharm中的调试(debug)
Nov 29 Python
python虚拟环境迁移方法
Jan 03 Python
通过python的matplotlib包将Tensorflow数据进行可视化的方法
Jan 09 Python
django用户登录验证的完整示例代码
Jul 21 Python
python实现126邮箱发送邮件
May 20 Python
python实现批量转换图片为黑白
Jun 16 Python
python与idea的集成的实现
Nov 20 Python
Django解决frame拒绝问题的方法
Dec 18 Python
Python爬虫之Selenium库的使用方法
Jan 03 Python
Python matplotlib绘制条形统计图 处理多个实验多组观测值
Apr 21 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数组函数序列之array_unshift() 在数组开头插入一个或多个元素
2011/11/07 PHP
php实现获取文件mime类型的方法
2015/02/11 PHP
JavaScript中的Window窗口对象
2008/01/16 Javascript
JavaScript 学习技巧
2010/02/17 Javascript
jQuery中attr()方法用法实例
2015/01/05 Javascript
jQuery实现自定义事件的方法
2015/04/17 Javascript
js获取字符串字节数方法小结
2015/06/09 Javascript
JavaScript 正则表达式中global模式的特性
2016/02/25 Javascript
Extjs4.0 ComboBox如何实现三级联动
2016/05/11 Javascript
js验证真实姓名与身份证号,手机号的简单实例
2016/07/18 Javascript
JavaScript数据类型学习笔记分享
2016/09/01 Javascript
nodejs实现爬取网站图片功能
2017/12/14 NodeJs
详解Vue中localstorage和sessionstorage的使用
2017/12/22 Javascript
详解create-react-app 2.0版本如何启用装饰器语法
2018/10/23 Javascript
vue中axios实现数据交互与跨域问题
2019/05/12 Javascript
jquery validate 实现动态增加/删除验证规则操作示例
2019/10/28 jQuery
js中位数不足自动补位扩展padLeft、padRight实现代码
2020/04/06 Javascript
原生JavaScript实现随机点名表
2021/01/14 Javascript
在Python中测试访问同一数据的竞争条件的方法
2015/04/23 Python
python连接MySQL数据库实例分析
2015/05/12 Python
python实现zabbix发送短信脚本
2018/09/17 Python
python3对拉勾数据进行可视化分析的方法详解
2019/04/03 Python
centos 安装Python3 及对应的pip教程详解
2019/06/28 Python
python如何实现从视频中提取每秒图片
2020/10/22 Python
python 类之间的参数传递方式
2019/12/20 Python
Python查找不限层级Json数据中某个key或者value的路径方式
2020/02/27 Python
Python并发concurrent.futures和asyncio实例
2020/05/04 Python
python爬虫---requests库的用法详解
2020/09/28 Python
CSS3 filter(滤镜)实现网页灰色或者黑色模式的代码
2020/11/30 HTML / CSS
口腔工艺技术专业毕业生自荐信
2013/09/27 职场文书
小学标准化建设汇报材料
2014/08/16 职场文书
高中课前三分钟演讲稿
2014/09/13 职场文书
党的群众路线对照检查材料范文
2014/09/24 职场文书
党员组织生活会发言材料
2014/10/17 职场文书
2014年大学班长工作总结
2014/11/14 职场文书
原告离婚代理词
2015/05/23 职场文书