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中的测试模块unittest和doctest的使用教程
Apr 14 Python
Python中绑定与未绑定的类方法用法分析
Apr 29 Python
Python正则表达式教程之三:贪婪/非贪婪特性
Mar 02 Python
Python实现的文本编辑器功能示例
Jun 30 Python
python3之微信文章爬虫实例讲解
Jul 12 Python
用Python写一段用户登录的程序代码
Apr 22 Python
python 平衡二叉树实现代码示例
Jul 07 Python
python通过txt文件批量安装依赖包的实现步骤
Aug 13 Python
Django 拆分model和view的实现方法
Aug 16 Python
30秒学会30个超实用Python代码片段【收藏版】
Oct 15 Python
python实现的分层随机抽样案例
Feb 25 Python
Python中的 No Module named ***问题及解决
Jul 23 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
ftp类(example.php)
2006/10/09 PHP
PHP编程之高级技巧——利用Mysql函数
2006/10/09 PHP
PHP判断搜索引擎蜘蛛并自动记忆到文件的代码
2012/02/04 PHP
php将字符串转换成16进制的方法
2015/03/17 PHP
PHP使用内置函数file_put_contents写入文件及追加内容的方法
2015/12/07 PHP
Yii清理缓存的方法
2016/01/06 PHP
php进行ip地址掩码运算处理的方法
2016/07/11 PHP
ubutu 16.04环境下,PHP与mysql数据库,网页登录验证实例讲解
2017/07/20 PHP
微信公众平台开发教程②微信端分享功能图文详解
2019/04/10 PHP
php探针不显示内存解决方法
2019/09/17 PHP
JavaScript Cookie显示用户上次访问的时间和次数
2009/12/08 Javascript
判断复选框是否被选中的两种方法
2014/06/04 Javascript
jquery实现拖拽调整Div大小
2015/01/30 Javascript
JavaScript实现强制重定向至HTTPS页面
2015/06/10 Javascript
Bootstrap基础学习
2015/06/16 Javascript
jquery实现仿新浪微博评论滚动效果
2015/08/06 Javascript
JS组件系列之Bootstrap table表格组件神器【终结篇】
2016/05/10 Javascript
AngularJS使用指令增强标准表单元素功能
2016/07/01 Javascript
自动化测试读写64位操作系统的注册表
2016/08/15 Javascript
Bootstrap的Carousel配合dropload.js实现移动端滑动切换图片
2017/03/10 Javascript
深入浅出webpack教程系列_安装与基本打包用法和命令参数详解
2017/09/10 Javascript
jQuery轻量级表单模型验证插件
2018/10/15 jQuery
pm2启动ssr失败的解决方法
2019/06/29 Javascript
使用eslint和githooks统一前端风格的技巧
2020/07/29 Javascript
[51:00]Secret vs VGJ.S 2018国际邀请赛淘汰赛BO3 第一场 8.24
2018/08/25 DOTA
Python continue继续循环用法总结
2018/06/10 Python
python 实现弹球游戏的示例代码
2020/11/17 Python
HTML5 语音搜索只需一句代码
2013/01/03 HTML / CSS
丹尼尔惠灵顿手表天猫官方旗舰店:Daniel Wellington
2017/08/25 全球购物
英国在线发型和美容产品商店:Beauty Cutie
2019/04/27 全球购物
求职简历中个人的自我评价
2013/12/25 职场文书
发展部经理职责规定
2014/02/22 职场文书
教师群众路线教育实践活动个人对照检查材料
2014/11/04 职场文书
2016年端午节红领巾广播稿
2015/12/18 职场文书
「魔法少女伊莉雅」美游粘土人开订
2022/03/21 日漫
MySQL普通表如何转换成分区表
2022/05/30 MySQL