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中吸引人的一些特性
Apr 09 Python
Python multiprocessing模块中的Pipe管道使用实例
Apr 11 Python
使用Python对Csv文件操作实例代码
May 12 Python
Python实现网站注册验证码生成类
Jun 08 Python
详解Python3.6的py文件打包生成exe
Jul 13 Python
详解Python_shutil模块
Mar 15 Python
浅谈Python的条件判断语句if/else语句
Mar 21 Python
pycharm 批量修改变量名称的方法
Aug 01 Python
通过celery异步处理一个查询任务的完整代码
Nov 19 Python
python中wheel的用法整理
Jun 15 Python
解决jupyter notebook启动后没有token的坑
Apr 24 Python
使用pd.merge表连接出现多余行的问题解决
Jun 16 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
动态新闻发布的实现及其技巧
2006/10/09 PHP
PHPMailer邮件发送的实现代码
2013/05/04 PHP
函数中使用require_once问题深入探讨 优雅的配置文件定义方法推荐
2014/07/02 PHP
PHP开发框架kohana中处理ajax请求的例子
2014/07/14 PHP
php类的扩展和继承用法实例
2015/06/20 PHP
Laravel框架实现定时Task Scheduling例子
2019/10/22 PHP
js转义字符介绍
2013/11/05 Javascript
jquery css 设置table的奇偶行背景色示例
2014/06/03 Javascript
Jquery ajax加载等待执行结束再继续执行下面代码操作
2015/11/24 Javascript
js改变style样式和css样式的简单实例
2016/06/28 Javascript
Bootstrap基本样式学习笔记之按钮(4)
2016/12/07 Javascript
jQuery validate插件功能与用法详解
2016/12/15 Javascript
关于jQuery库冲突的完美解决办法
2017/05/20 jQuery
深入理解angular2启动项目步骤
2017/07/15 Javascript
详解React native全局变量的使用(跨组件的通信)
2017/09/07 Javascript
微信小程序实现导航栏选项卡效果
2020/06/19 Javascript
vue脚手架及vue-router基本使用
2018/04/09 Javascript
取消Bootstrap的dropdown-menu点击默认关闭事件方法
2018/08/10 Javascript
JavaScript观察者模式原理与用法实例详解
2020/03/10 Javascript
js实现简单进度条效果
2020/03/25 Javascript
Python常用算法学习基础教程
2017/04/13 Python
python编程通过蒙特卡洛法计算定积分详解
2017/12/13 Python
详解python配置虚拟环境
2019/04/08 Python
NumPy 基本切片和索引的具体使用方法
2019/04/24 Python
python多线程+代理池爬取天天基金网、股票数据过程解析
2019/08/13 Python
Django实现简单的分页功能
2021/02/22 Python
高一自我鉴定
2013/12/17 职场文书
竞争上岗演讲稿
2014/01/05 职场文书
五年级英语教学反思
2014/01/31 职场文书
中学生励志演讲稿
2014/04/26 职场文书
2016年秋季新学期致辞
2015/07/30 职场文书
会计做账心得体会
2016/01/22 职场文书
纪检干部学习心得体会
2016/01/23 职场文书
my.ini优化mysql数据库性能的十个参数(推荐)
2021/05/26 MySQL
Spring Boot项目传参校验的最佳实践指南
2022/04/05 Java/Android
JS前端轻量fabric.js系列物体基类
2022/08/05 Javascript