Python 分析Nginx访问日志并保存到MySQL数据库实例
时间:2024-01-22 08:43:23
使用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,Nginx访问日志
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python @classmethod 的使用场合详解
2023-08-02 20:50:35
python视频按帧截取图片工具
2021-09-08 10:30:56
JS变量中有var定义和无var定义的区别以及es6中let命令和const命令
2024-05-22 10:37:29
![](https://img.aspxhome.com/file/2023/0/123410_0s.jpg)
asp当中判断函数一览
2010-05-27 12:15:00
pandas 把数据写入txt文件每行固定写入一定数量的值方法
2021-06-13 20:08:14
![](https://img.aspxhome.com/file/2023/4/87734_0s.jpg)
Ubuntu18.04下python版本完美切换的解决方法
2021-08-22 11:24:19
![](https://img.aspxhome.com/file/2023/9/112129_0s.jpg)
js贪吃蛇游戏实现思路和源码
2024-04-10 11:03:57
![](https://img.aspxhome.com/file/2023/8/136798_0s.jpg)
Vue 2.0+Vue-router构建一个简单的单页应用(附源码)
2024-05-10 14:17:43
![](https://img.aspxhome.com/file/2023/0/126460_0s.png)
Python排序算法之堆排序算法
2023-01-17 02:00:55
![](https://img.aspxhome.com/file/2023/3/63933_0s.png)
FCKEditor v2.6 编辑器配置图解教程
2024-01-04 22:16:05
![](https://img.aspxhome.com/file/2023/8/70638_0s.jpg)
AJAX打造博客无刷新搜索
2007-08-23 08:48:00
Node.js服务器开启Gzip压缩教程
2024-04-22 22:14:49
![](https://img.aspxhome.com/file/2023/3/136063_0s.png)
Python 实现定积分与二重定积分的操作
2023-08-05 18:22:27
![](https://img.aspxhome.com/file/2023/0/90810_0s.png)
CSS实现完美垂直居中
2007-09-22 09:29:00
javascript中传统事件与现代事件
2024-04-10 11:02:57
SQL Server 数据库基础编程详解
2024-01-17 03:29:37
python获取linux系统信息的三种方法
2022-04-13 06:27:55
使用python 将图片复制到系统剪贴中
2021-12-03 22:34:11
k-means 聚类算法与Python实现代码
2022-02-01 02:55:22
![](https://img.aspxhome.com/file/2023/7/99277_0s.png)
使用Python的Flask框架来搭建第一个Web应用程序
2022-12-11 21:46:10
![](https://img.aspxhome.com/file/2023/6/94126_0s.png)