Python获取Nginx访问日志,写入数据库

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

import pymysql
import re
import datetime
import sys
import time

# DB variables
dbhost = "192.168.189.185"
dbport = 3306
dbuser = ‘root‘
dbpassword = ‘********‘
charset = ‘utf8‘
log_file = sys.argv[1]

# 连接数据库
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)

# monitor access log

pos = 0
while True:
fd = open(log_file)
if pos != 0:
fd.seek(pos, 0)
while True:
line = fd.readline()
if line.strip():
logdata=line.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)
# 插入数据SQL语句
insert_sql = "INSERT INTO nginx.accesslog(IP, TIME, Method, Status, bytesSent, Request_time, Host) values(‘%s‘,‘%s‘,‘%s‘,‘%d‘,‘%d‘, ‘%f‘,‘%s‘);" % (ip, Time, method, int(status), int(bytesSent), float(request_time), Host)

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

pos = pos + len(line)
if not line.strip():
break

fd.close()
time.sleep(1)

cursor.close()
conn_db.close()

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

时间: 2024-08-25 21:12:27

Python获取Nginx访问日志,写入数据库的相关文章

Python基于nginx访问日志并统计IP访问量

如果想看看Nginx有多少IP访问量,有哪些国家访问,并显示IP地址的归属地分布,python可以结合使用高春辉老师ipip.net[免费版 IP 地址数据库],Shell可以使用nali,我这边主要使用python语言来实现需求,并将查询结果以邮件形式发送,也是为了学习和回顾python语言.很感谢高春辉老师提供的免费版IP地址数据库. 一.Ningx日志如下: 41.42.97.104 - - [26/Feb/2015:03:35:40 -0500] "GET /root/ HTTP/1.1

python统计apache、nginx访问日志IP访问次数并且排序(显示前20条)

前言:python统计apache.nginx访问日志IP访问次数并且排序(显示前20条).其实用awk+sort等命令可以实现,用awk数组也可以实现,这里只是用python尝试下. apache脚本: ips = {} with open("/root/mail_access_log-20180629") as fh:     for line in fh:         ip = line.split(" ")[0]         if 6 < le

自定义nginx访问日志和内置变量使用

自定义nginx访问日志和内置变量使用 安装第三方echo模块后查看内置变量 内置变量 1.$args 用户在浏览器中查找的相关参数(uri中?之后的字段)2.$document_root 站点根目录所在的位置3.$document_uri 去除url中域名部分后所剩下的目录4.$host 所访问的主机5.$http_user_agent 客户端所使用的浏览器6.$http_cookie 客户端的cookie信息7.$limit_rate 客户端的下载速率0表示不限制速度 server { se

ELK之六-----logstash结合redis收集系统日志和nginx访问日志

一.logstash结合redis收集系统日志 架构图: 环境准备: A主机:elasticsearch主机     IP地址:192.168.7.100 B主机:logstash主机            IP地址:192.168.7.102 C主机:redis主机                IP地址:192.168.7.103 D主机:logstash主机/nginx主机          IP地址:192.168.7.101 1.安装并配置redis 1.安装并配置redis服务,并启

Nginx 访问日志增长暴增出现尖刀的详细分析

前言:          Nginx日志里面Mobileweb_access.log增长特别大,一天上百兆,将近100W的访问记录,按照我们目前的规模,热点用户才500个左右,就算人人用手机app访问,怎么可能会有这么大的url访问量?以前只是安装使用nginx,还没有抽出时间仔细研究,这回需要彻底的去分析nginx日志了. 1,日志分类 主要2种,一种是错误日志,一种是访问日志,这些配置都在/usr/local/nginx/conf/nginx.conf里面,默认都是打开的,自己也可以选择关闭

nginx访问日志配置+日志切割+不记录静态文件日志+设置静态文件过期时间

nginx访问日志 查看nginx.conf文件 vim /usr/local/nginx/conf/nginx.conf 中间有一行是定义log的格式 log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]' ' $host "$request_uri" $status' ' "$http_referer" "$http_user_agent"';

今晚九点|如何使用 Python 分析 web 访问日志?

主题:如何使用 Python 分析 Web 访问日志 内容 Python 基础 字符串.字典.文件.时间 Web 访问日志 实战 提问 主讲师:KK 多语言混搭工程师,热爱开源技术,喜欢GET新技能,5年 PHP.Python 项目开发经验,带领团队完成多个中.小型项目开发,对安全.云等多个领域富有浓厚兴趣,擅长于 WEB 安全开发.性能优化.分布式应用开发&设计等多方面,做事认真负责,乐于分享技能,现任 51Reboot.com Python 实战班讲师 任何语言都有使用场景,只有合适和不合适

LNMP(2)Nginx默认虚拟主机、Nginx用户认证、Nginx域名重定向、Nginx访问日志、

Nginx默认虚拟主机 Nginx和httpd都有虚拟主机,在httpd中第一个被加载的就是默认虚拟主机:但是在Nginx中它有一个配置用来标记默认虚拟主机(default_server),如果不做标记,那么第一个也是默认为虚拟主机. 默认虚拟主机设置: 1.需改配置文件/usr/local/nginx/conf/nginx.conf cd /usr/local/nginx/conf/ vim nginx.conf 删除内容后,加上一行(在httpd{}里加)include vhost/*.co

48.Nginx访问日志、Nginx日志切割、静态文件不记录日志和过期时间

一.Nginx访问日志 日志格式 vim /usr/local/nginx/conf/nginx.conf //搜索log_format combined_realip //规则名字 除了在主配置文件nginx.conf里定义日志格式外,还需要在虚拟主机配置文件中增加 vim /usr/local/nginx/conf/vhost/test.com.conf 添加 access_log /tmp/1.log combined_realip; 这里的combined_realip就是在nginx.