通过python操作GeoLite2-City.mmdb库将nginx日志写入数据库

# 创建存放nginx日志的表accesslog2

  1. CREATE TABLE `accesslog2` (
  2. `id` bigint(20) NOT NULL AUTO_INCREMENT,
  3. `logtime` datetime DEFAULT NULL,
  4. `ip` varchar(128) DEFAULT NULL,
  5. `url` text,
  6. `status` int(11) DEFAULT NULL,
  7. `lat` float DEFAULT NULL,
  8. `lng` float DEFAULT NULL,
  9. `city` varchar(50) DEFAULT NULL,
  10. PRIMARY KEY (`id`)
  11. ) ENGINE=InnoDB AUTO_INCREMENT=896 DEFAULT CHARSET=utf8;

# 安装geoip2模块
# sudo pip2 install geoip2

  1. #encoding=utf-8
  2.  
  3. import time
  4. import geoip2.database
  5.  
  6. from dbutils import MysqlConnection
  7.  
  8. # 找出ip所在城市的日志处理
  9. def log_2db_4map(log_file):
  10. # 清空数据库信息
  11. MysqlConnection.execute_sql('truncate table accesslog2')
  12. path=log_file
  13. shandle = open(path, 'r')
  14. log_dict = {}
  15.  
  16. # 读取ip数据库
  17. reader = geoip2.database.Reader('GeoLite2-City.mmdb')
  18.  
  19. while True:
  20. line = shandle.readline()
  21. if line == '':
  22. break
  23. _nodes = line.split()
  24.  
  25. # 访问url,来访ip,http状态码,访问时间
  26. _url,_ip,_status,_lgtime = _nodes[6], _nodes[0], _nodes[8],_nodes[3][1:]
  27.  
  28. # 将日志访问的时间"22/Oct/2017:03:28:01"转成 2017-11-23 10:08:18 类似的格式
  29. _ltime = time.strftime('%Y-%m-%d %H:%M:%S',time.strptime(_lgtime,'%d/%b/%Y:%H:%M:%S'))
  30. # 获取城市信息
  31. try:
  32. response = reader.city(_ip)
  33. # 如果国家不是中国跳出本次循环
  34. if 'China' != response.country.name:
  35. continue
  36. # 获取城市
  37. _city = response.city.names.get('zh-CN','')
  38. if _city == '':
  39. print 'ip: %s city is empty' % _ip
  40. continue
  41. # 获取经度和纬度
  42. _lat = response.location.latitude
  43. _lng = response.location.longitude
  44. # print response
  45. except Exception as e:
  46. print 'goe has not %s info' % _ip
  47.  
  48. _args = (_ltime,_ip,_url,_status, _lat,_lng,_city)
  49. # 插入数据库语句
  50. sql = 'insert into accesslog2(logtime, ip, url,status,lat,lng,city) values(%s, %s, %s,%s,%s,%s,%s)'
  51. MysqlConnection.execute_sql(sql, _args)
  52.  
  53. # 关闭文件句柄
  54. shandle.close()
  55.  
  56. # 文件入口
  57. if __name__ == '__main__':
  58. # nginx日志文件
  59. log_file = 'www_access.log'
  60. rt_list = log_2db_4map(log_file = log_file)

连接数据库和操作数据库的底层模块参考:
python操作mysql数据库增删改查的dbutils实例
http://www.cnblogs.com/reblue520/p/7884365.html

通过python操作GeoLite2-City.mmdb库将nginx日志访问IP转换为城市写入数据库的更多相关文章

  1. python 操作excle 之第三方库 openpyxl学习

    目录 python 操作excle 之第三方库 openpyxl学习 安装 pip install openpyxl 英文文档链接 : 点击这里~ 1,定位excel 2,读取excle中的内容 3, ...

  2. 操作文件-取出一个60s内log日志中ip访问次数超过100次的ip

    import timea=0while True: d={} f = open(r"/Users/**juan/Downloads/access.log",encoding=&qu ...

  3. 数据库之redis篇(3)—— Python操作redis

    虽然前面两篇已经说了redis的一些配置安装什么的,篇幅有点长,可能看完了也不知道怎么操作,这里再浓缩一下: 什么是redis redis完全开源免费的,遵守BSD协议,是一个高性能的非关系型key- ...

  4. 【踩坑记录】记录一次使用Python logging库多进程打印日志的填坑过程

    背景: 项目使用Python自带的logging库来打印日志 项目部署在一台Centos7的机器上 项目采用gunicorn多进程部署 过程: 1.LOG日志代码封装: 采用logging库,并设置w ...

  5. 学会用Python操作Mongodb

    在linux下,用pip导包. pip install pymongo python操作基本步骤: 导包 建立连接,建立客户端. 获取数据库 获取集合 对数据操作 import pymongo #建立 ...

  6. 利用python分析nginx日志

    最近在学习python,写了个脚本分析nginx日志,练练手.写得比较粗糙,但基本功能可以实现. 脚本功能:查找出当天访问次数前十位的IP,并获取该IP来源,并将分析结果发送邮件到指定邮箱. 实现前两 ...

  7. python操作Excel,你觉得哪个库更好呢?

    对比学习python,更高效~ Excel数据的类型及组织方式 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很多已经做案例的人,却不知 ...

  8. Python 操作 MS Excel 文件

    利用 Python 对 Excel 文件进行操作需要使用第三方库: openpyxl,可执行 pip install openpyxl 进行安装 1. 导入 openpyxl 模块 导入 openpy ...

  9. python学习笔记-(十六)python操作mysql

    一. mysql安装 1. windows下安装mysql 1.1. 下载源: http://dev.mysql.com/downloads/installer/,请认准对应版本 Windows (x ...

随机推荐

  1. 学习总结:CSS(一)定义方式、选择器、选择器权重

    一.CSS的定义方式 1.内部样式:<style></style> 2.行间样式:<div style="width:100px;height:100px;&q ...

  2. 【1】【leetcode-93】复原IP地址

    (不会,典型) 给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式. 示例: 输入: "25525511135" 输出: ["255.255.11.135 ...

  3. Shell编程(五)脚本语法

    ${}: 数据“内容”删除,替换:{}: 列表 1. 条件测试: test =~:正则匹配 2. if/then/elif/else/fi #!/bin/bash echo "Is it o ...

  4. Shell编程(三)Shell特性

    !$:显示上一条命令最后一个参数 $?: 上个命令的退出状态,或函数的返回值. alias xxx="命令":给命令取别名 xxx 通过 vim ~/.bashrc 里编辑,可以来 ...

  5. hadoop的基本概念 伪分布式hadoop集群的安装 hdfs mapreduce的演示

    hadoop 解决问题: 海量数据存储(HDFS) 海量数据的分析(MapReduce) 资源管理调度(YARN)

  6. 六、文件IO——fcntl 函数 和 ioctl 函数

    6.1 fcntl 函数 6.1.1 函数介绍 #include <unistd.h> #include <fcntl.h> int fcntl(int fd, int cmd ...

  7. Generic XXE Detection

    参考连接:https://www.christian-schneider.net/GenericXxeDetection.html In this article I present some tho ...

  8. EL 快速开始

    技术选型上,推荐使用EL表达式,少用不用taglib. 大趋势 前后端分离 mvc+mvvm ,使用[thymeleaf]和前端更好结合,也是springboot官方推荐的做法. [viewTicke ...

  9. Xshell 无法连接虚拟机中的ubuntu的问题

     转自:http://blog.csdn.net/qq_26941173/article/details/51173320 版权声明:本文为博主原创文章,未经博主允许不得转载. 昨天在VMware P ...

  10. kindeditor编辑器上传图片

    使用的是asp.net MVC 上传图片. 1.下载Kindeditor的对应的包 2.html页面 @{ Layout = null; } <!DOCTYPE html> <htm ...