python 将nginx日志写得mysql
#/usr/bin/env python
#-*-coding:UTF-8 -*-
from datetime import datetime
import pymysql
connect=pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='',
database='nginxlog',
charset="utf8"
)
cur = connect.cursor()
sql= "insert into nginxlog(ip,time,methods,source,protocol,status) values(%s,%s,%s,%s,%s,%s)"
with open("D:/tools/nginx-1.17.9/logs\host.access.log","r") as ngfile:
for line in ngfile:
_nodes = line.split()
IP= _nodes[0]
Time= _nodes[3][1:-1].replace(":"," ",1) #将时间转换为17/Jun/2017 12:43:4格式
Time = datetime.strptime(Time,"%d/%b/%Y %H:%M:%S")#将时间格式化为2017-06-17 12:43:04
Methods = _nodes[5][1:]
Source = _nodes[6]
Protocol = _nodes[7][:-1]
Status = _nodes[8]
print(IP,Time,Methods,Source,Protocol,Status)
cur.execute(sql,(IP,Time,Methods,Source,Protocol,Status))
connect.commit()
connect.close()
发表评论 (审核通过后显示评论):