利用Python实现读取Nginx日志,并将需要信息写入到数据库。

#!/usr/bin/env python
# coding: utf-8
# Auther:liangkai
# Date:2018/6/26 11:26
# License: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited.
# Describe:

import pymysql
import re
import datetime

# DB variables
dbhost = "192.168.189.185"
dbport = 3306
dbuser = ‘root‘
dbpassword = ‘123456‘
charset = ‘utf8‘

# 连接数据库
conn_db = pymysql.connect(host=dbhost,port=dbport,user=dbuser,password=dbpassword,charset=charset)
cursor=conn_db.cursor()

# 创建数据库
cursor.execute("create database if not exists nginx")

# 创建表
create_table = ‘‘‘create table nginx.accesslog( id int(4), IP char(20), time timestamp, Method char(4), Status int(4),Request_time float(4), X_Forwarded_for char(8),Host char(20),primary key(id) );
‘‘‘
cursor.execute(create_table)

# Nginx log variables
with open("zabbix.eub-inc.com.access.log",‘r‘) as f:
list = f.readlines()

for i in range(0,len(list)):
logdata = list[i].strip()
matchObj = re.search(r‘(.*) - - \[(.*)\] \"(.*) (\/.*)\" (.*) (.*) (.*) \"(.*)\" \"(.*)\" \"(.*)\" \"(.*)\"‘,logdata)

if matchObj != None:
ip = matchObj.group(1)
time = matchObj.group(2)[0:20]
method = matchObj.group(3)
request = matchObj.group(4)
status = int(matchObj.group(5))
bytesSent = int(matchObj.group(6))
request_time = float(matchObj.group(7))
refer = matchObj.group(8)
agent = matchObj.group(9)
X_Forwarded_for = matchObj.group(10)
Host = matchObj.group(11)

# 时间格式化为mysql数据库支持的格式
format = ‘%d/%b/%Y:%H:%M:%S‘
time = datetime.datetime.strptime(time, format)
print(time)
# 插入数据SQL语句
sql = "INSERT INTO nginx.accesslog(IP, TIME, Method, Status, Request_time, Host) values(‘%s‘,‘%s‘,‘%s‘,‘%d‘,‘%f‘,‘%s‘);" %(ip,time,method,int(status),float(request_time),Host)

# 执行插入语句
try:
cursor.execute(sql)
conn_db.commit()
print("insert Ok")
except:
conn_db.rollback()
print("insert Error !!!")

cursor.close()
conn_db.close()

原文地址:http://blog.51cto.com/liangkai/2135634

时间: 2024-11-06 09:57:08

利用Python实现读取Nginx日志,并将需要信息写入到数据库。的相关文章

python——nagios监控nginx日志 request_time

遇到问题:nginx日志包含非常重要的信息.比如upstream_response_time 和request_time.现需求监控改值. 解决问题:编写python脚本,通过nagios check_nrpe 插件完成监控. 前提了解: nginx日志格式: log_format  main  '$remote_addr |$time_local| $request | $status | $body_byte s_sent | $http_referer | $http_user_agent

python利用inotify实现把nginx日志实时写入数据库

利用了pyinotify库,我用的是这里的这个,https://github.com/seb-m/pyinotify 其实网上yum上也有pyinotify库可以安装. 写入数据库是pymysql这里做一下记录, 先务pyinotify实现一个tail -f 的功能: #!/opt/python3/bin/python3 # import pyinotify import time import os import sys class ProcessTransientFile(pyinotify

python 分析处理nginx日志

临时帮公司研发同事处理nginx日志,凑合了一个脚本,用着还行,执行效率,还可以吧,一个G的文件,一分钟内就可以处理完成,供大家参考. #!/usr/bin/env python import os import re import fileinput logfile = r"/data/log20140904/nginx/192.168.1.50" #定义正则匹配变量 ip = r"?P<ip>[\d.]*" timeP = r""

python 正则分析nginx日志

有个需求要分析nginx日志,也懒得去研究logstach之类的开源工具,干脆直接写一个脚本,自己根据需求来实现: 先看日志格式:我们跟别人的不太一样,所以没办法了: 12.195.166.35 [10/May/2015:14:38:09 +0800] "list.xxxx.com" "GET /new/10:00/9.html?cat=0,0&sort=price_asc HTTP/1.0" 200 42164 "http://list.zhon

一个简易的python脚本统计nginx日志里的url及大小

log 日志格式如下 113.221.56.131 - [05/Feb/2015:18:31:19 +0800] " ab.baidu.com GET /media/game/a_.jpg HTTP/1.1" 200 169334 "http://laoma123.ybgj01.com/" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQWubi 133)" " 11

Python读取NGINX日志将其存入数据库

日志数据: #/usr/bin/env python #-*-coding:UTF-8 -*- from  datetime  import  datetime stat_days = [] import   pymysql #print(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) #2018-05-25 22:23:44 #print(datetime.now().strftime("%d/%b-%Y %H:%M:%S&quo

利用ngxtop工具对nginx日志实时分析

参考:通过ngxtop实时监控webserver的访问情况 一.部署 准备:python2.7.3+.SQLite(否则会报错) 编译安装SQLite cd /usr/local/src && wget    #下载安装包,最新安装包请参考 tar xf sqlite-autoconf-3230100.tar.gz && cd sqlite-autoconf-3230100  #解压安装包 ./configure --prefix=/usr/local/sqlite &am

filebeat读取nginx日志并写入kafka

filebeat写入kafka的配置: filebeat.inputs: - type: log paths: - /tmp/access.log tags: ["nginx-test"] fields: type: "nginx-test" log_topic: "nginxmessages" fields_under_root: true processors: - drop_fields: fields: ["beat"

php读取xml文件内容,并循环写入mysql数据库

<?php $dbconn = mysql_connect("localhost","root","root"); $db = mysql_select_db("xbrl",$dbconn); $xml = simplexml_load_file("test.xml"); $name = "" ; $price = 0.00 ; foreach ($xml->children