Python 分析Nginx訪問日志并保存到MySQL數(shù)據(jù)庫實(shí)例
更新時(shí)間:2014年03月13日 09:13:56 作者:
這篇文章主要介紹了Python 分析Nginx訪問日志并保存到MySQL數(shù)據(jù)庫實(shí)例,需要的朋友可以參考下
使用Python 分析Nginx access 日志,根據(jù)Nginx日志格式進(jìn)行分割并存入MySQL數(shù)據(jù)庫。
一、Nginx access日志格式如下:
復(fù)制代碼 代碼如下:
$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"' #使用的是nginx默認(rèn)日志格式
二、Nginx access 日志內(nèi)容如下:
復(fù)制代碼 代碼如下:
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代碼:
復(fù)制代碼 代碼如下:
#!/usr/bin/env python
#coding:utf8
import os
import fileinput
import re
import sys
import MySQLdb
#日志的位置
logfile=open("access_20130812.log")
#使用的nginx默認(rèn)日志格式$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"'
#日志分析正則表達(dá)式
#203.208.60.230
ipP = r"?P<ip>[\d.]*"
#以[開始,除[]以外的任意字符 防止匹配上下個(gè)[]項(xiàng)目(也可以使用非貪婪匹配*?) 不在中括號(hào)里的.可以匹配換行外的任意字符 *這樣地重復(fù)是"貪婪的“ 表達(dá)式引擎會(huì)試著重復(fù)盡可能多的次數(shù)。#以]結(jié)束
#[21/Jan/2011:15:04:41 +0800]
timeP = r"""?P<time>\[[^\[\]]*\]"""
#以"開始, #除雙引號(hào)以外的任意字符 防止匹配上下個(gè)""項(xiàng)目(也可以使用非貪婪匹配*?),#以"結(jié)束
#"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+"
#以"開始, 除雙引號(hào)以外的任意字符 防止匹配上下個(gè)""項(xiàng)目(也可以使用非貪婪匹配*?),#以"結(jié)束
#"http://test.myweb.com/myAction.do?method=view&mod_id=&id=1346"
referP = r"""?P<refer>\"[^\"]*\""""
#以"開始, 除雙引號(hào)以外的任意字符 防止匹配上下個(gè)""項(xiàng)目(也可以使用非貪婪匹配*?),以"結(jié)束
#"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"'
userAgentP = r"""?P<userAgent>\"[^\"]*\""""
#以(開始, 除雙引號(hào)以外的任意字符 防止匹配上下個(gè)()項(xiàng)目(也可以使用非貪婪匹配*?),以"結(jié)束
#(compatible; Googlebot/2.1; +http://www.google.com/bot.html)"'
userSystems = re.compile(r'\([^\(\)]*\)')
#以"開始,除雙引號(hào)以外的任意字符防止匹配上下個(gè)""項(xiàng)目(也可以使用非貪婪匹配*?),以"結(jié)束
userlius = re.compile(r'[^\)]*\"')
#原理:主要通過空格和-來區(qū)分各不同項(xiàng)目,各項(xiàng)目內(nèi)部寫各自的匹配表達(dá)式
nginxLogPattern = re.compile(r"(%s)\ -\ -\ (%s)\ (%s)\ (%s)\ (%s)\ (%s)\ (%s)" %(ipP, timeP, requestP, statusP, bodyBytesSentP, referP, userAgentP), re.VERBOSE)
#數(shù)據(jù)庫連接信息
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()
#coding:utf8
import os
import fileinput
import re
import sys
import MySQLdb
#日志的位置
logfile=open("access_20130812.log")
#使用的nginx默認(rèn)日志格式$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"'
#日志分析正則表達(dá)式
#203.208.60.230
ipP = r"?P<ip>[\d.]*"
#以[開始,除[]以外的任意字符 防止匹配上下個(gè)[]項(xiàng)目(也可以使用非貪婪匹配*?) 不在中括號(hào)里的.可以匹配換行外的任意字符 *這樣地重復(fù)是"貪婪的“ 表達(dá)式引擎會(huì)試著重復(fù)盡可能多的次數(shù)。#以]結(jié)束
#[21/Jan/2011:15:04:41 +0800]
timeP = r"""?P<time>\[[^\[\]]*\]"""
#以"開始, #除雙引號(hào)以外的任意字符 防止匹配上下個(gè)""項(xiàng)目(也可以使用非貪婪匹配*?),#以"結(jié)束
#"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+"
#以"開始, 除雙引號(hào)以外的任意字符 防止匹配上下個(gè)""項(xiàng)目(也可以使用非貪婪匹配*?),#以"結(jié)束
#"http://test.myweb.com/myAction.do?method=view&mod_id=&id=1346"
referP = r"""?P<refer>\"[^\"]*\""""
#以"開始, 除雙引號(hào)以外的任意字符 防止匹配上下個(gè)""項(xiàng)目(也可以使用非貪婪匹配*?),以"結(jié)束
#"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"'
userAgentP = r"""?P<userAgent>\"[^\"]*\""""
#以(開始, 除雙引號(hào)以外的任意字符 防止匹配上下個(gè)()項(xiàng)目(也可以使用非貪婪匹配*?),以"結(jié)束
#(compatible; Googlebot/2.1; +http://www.google.com/bot.html)"'
userSystems = re.compile(r'\([^\(\)]*\)')
#以"開始,除雙引號(hào)以外的任意字符防止匹配上下個(gè)""項(xiàng)目(也可以使用非貪婪匹配*?),以"結(jié)束
userlius = re.compile(r'[^\)]*\"')
#原理:主要通過空格和-來區(qū)分各不同項(xiàng)目,各項(xiàng)目內(nèi)部寫各自的匹配表達(dá)式
nginxLogPattern = re.compile(r"(%s)\ -\ -\ (%s)\ (%s)\ (%s)\ (%s)\ (%s)\ (%s)" %(ipP, timeP, requestP, statusP, bodyBytesSentP, referP, userAgentP), re.VERBOSE)
#數(shù)據(jù)庫連接信息
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()
四、存入數(shù)據(jù)庫后數(shù)據(jù)是如下圖:
您可能感興趣的文章:
- Python logging日志庫空間不足問題解決
- python GUI庫圖形界面開發(fā)之PyQt5中QWebEngineView內(nèi)嵌網(wǎng)頁與Python的數(shù)據(jù)交互傳參詳細(xì)方法實(shí)例
- python GUI庫圖形界面開發(fā)之PyQt5瀏覽器控件QWebEngineView詳細(xì)使用方法
- Python中l(wèi)ogging日志庫實(shí)例詳解
- 在Python中使用MongoEngine操作數(shù)據(jù)庫教程實(shí)例
- python中l(wèi)ogging庫的使用總結(jié)
- win系統(tǒng)下為Python3.5安裝flask-mongoengine 庫
- python logging類庫使用例子
- 聊聊python的gin庫的介紹和使用
相關(guān)文章
Python如何根據(jù)字幕文件自動(dòng)給視頻添加字幕效果
視頻中字幕的重要性不用多說了,下面這篇文章主要給大家介紹了關(guān)于Python如何根據(jù)字幕文件自動(dòng)給視頻添加字幕效果的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-02-02
python 遍歷列表提取下標(biāo)和值的實(shí)例
今天小編就為大家分享一篇python 遍歷列表提取下標(biāo)和值的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
Python調(diào)用Elasticsearch更新數(shù)據(jù)庫的操作方法
Elasticsearch是一個(gè)分布式、多租戶的全文搜索引擎,支持HTTP Web接口和無模式的JSON文檔,本文介紹Python調(diào)用Elasticsearch更新數(shù)據(jù)庫的相關(guān)操作,感興趣的朋友一起看看吧2024-12-12
新手入門學(xué)習(xí)python Numpy基礎(chǔ)操作
這篇文章主要介紹了新手入門學(xué)習(xí)python Numpy基礎(chǔ)操作,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03
pandas數(shù)據(jù)處理基礎(chǔ)之篩選指定行或者指定列的數(shù)據(jù)
這篇文章主要介紹了pandas數(shù)據(jù)處理基礎(chǔ)之篩選指定行或者指定列的數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2018-05-05

