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

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介:

   如果想看看Nginx有多少IP访问量,有哪些国家访问,并显示IP地址的归属地分布,python可以结合使用高春辉老师ipip.net免费版 IP 地址数据库】,Shell可以使用nali,我这边主要使用python语言来实现需求,并将查询结果以邮件形式发送,也是为了学习和回顾python语言。很感谢高春辉老师提供的免费版IP地址数据库。


一、Ningx日志如下:

1
2
3
4
5
41.42.97.104 - - [26 /Feb/2015 :03:35:40 -0500]  "GET /root/ HTTP/1.1"  301 20  "http://baibai.123.com/09"  "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36"  - 0.562 
41.42.97.104 - - [26 /Feb/2015 :03:35:41 -0500]  "GET /crossadkla.xml HTTP/1.1"  304 0  "https://baibai.123.com/"  "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36"  - 0.000 
99.122.189.203 - - [26 /Feb/2015 :03:35:42 -0500]  "GET /root/ HTTP/1.1"  301 20  "http://baibai.123.com/11"  "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36"  - 0.562 
99.122.189.203  - - [26 /Feb/2015 :03:35:44 -0500]  "GET /crossadkla.xml HTTP/1.1"  304 0  "https://baibai.123.com/"  "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36"  - 0.000
99.122.189.203  - - [26 /Feb/2015 :03:35:44 -0500]  "GET /crossadkla.xml HTTP/1.1"  304 0  "https://baibai.123.com/"  "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36"  - 0.000

二、下载 免费版 IP 地址数据库

1
2
  #wget  http://s.qdcdn.com/17mon/17monipdb.zip
  #unzip  17monipdb.zip

三、IP库常见问题FAQ

 示例代码:

1
2
3
4
5
6
7
8
9
import  os
from  ipip  import  IP
from  ipip  import  IPX
 
IP.load(os.path.abspath( "mydata4vipday2.dat" ))
print  IP.find( "118.28.8.8" )
 
IPX.load(os.path.abspath( "mydata4vipday2.datx" ))
print  IPX.find( "118.28.8.8" )

 执行输出:

1
2
中国  天津  天津      鹏博士
中国  天津  天津      鹏博士   39.128399   117.185112  Asia /Shanghai    UTC+8   120000

 IP库guihub地址:https://github.com/17mon/python

四、Python 统计代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#encoding=utf8
 
import  re,sys,os,csv,smtplib
from  ipip  import  IP
from  ipip  import  IPX
from  email  import  encoders
from  email.mime.multipart  import  MIMEMultipart
from  email.mime.base  import  MIMEBase
from  email.mime.text  import  MIMEText
from  optparse  import  OptionParser
reload (sys)
sys.setdefaultencoding( 'utf-8' )
print  sys.getdefaultencoding()
 
nginx_log_path = "/app/nginx/logs/apptest_www.access.log"
pattern  =  re. compile (r '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' )
def  stat_ip_views(log_path):
     ret = {}
     =  open (log_path,  "r" )
     for  line  in  f:
         match  =  pattern.match(line)
         if  match:
             ip = match.group( 0 )
             if  ip  in  ret:
                 views = ret[ip]
             else :
                 views = 0
             views = views + 1
             ret[ip] = views
     return  ret
     
def  run():
     ip_views = stat_ip_views(nginx_log_path)
     max_ip_view = {}
     fileName = 'out.csv'
     f = open ( 'out.csv' , 'w+' )
     =  'IP,国家,访问数总数'
     print  >> f,b
     for  ip  in  ip_views:
         IP.load(os.path.abspath( "17monipdb.dat" ))
         count = IP.find( "%s" %  (ip))
         conut_s = count.split()
         countery = conut_s[ 0 ]
         views = ip_views[ip]
         =  '%s,%s,%s'  % (ip,countery,views)
         print  >> f,c
         if  len (max_ip_view) = = 0 :
             max_ip_view[ip] = views
         else :
             _ip = max_ip_view.keys()[ 0 ]
             _views = max_ip_view[_ip]
             if  views>_views:
                 max_ip_view[ip] = views
                 max_ip_view.pop(_ip)
         print  "IP:" , ip,  "国家:" , countery,  "访问数:" , views 
         
     print  "总共有多少IP:" len (ip_views)
     print  "最大访问IP数:" , max_ip_view
     =  ""
     =  '总共有多少IP:%s'  % ( len (ip_views))
     =  '最大访问IP数:%s'  % (max_ip_view)
     print  >> f,g
     print  >> f,d
     print  >> f,e
 
def  sendMail(html,emailaddress,mailSubject,from_address = "other@test.com" ):
         mail_list = emailaddress.split( "," )
         msg = MIMEMultipart()
         msg[ 'Accept-Language' ] = 'zh-CN'
         msg[ 'Accept-Charset' ] =  'ISO-8859-1,utf-8'
         msg[ 'From' ] = from_address
         msg[ 'to' ] = ";" .join(mail_list)
         msg[ 'Subject' ] = mailSubject.decode( "utf-8" )
         txt = MIMEText(html, 'html' , 'utf-8' )
         txt.set_charset( 'utf-8' )
         msg.attach(txt)
         file = MIMEBase( 'application' 'octet-stream' )
         file .set_payload( open (fileName,  'rb' ).read())
         encoders.encode_base64( file )
         file .add_header( 'Content-Disposition' 'attachment; filename="%s"'  %  os.path.basename(fileName))
         msg.attach( file )
         smtp = smtplib.SMTP( "mail.test.com" )
         smtp.sendmail(msg[ "From" ],mail_list,msg.as_string())
         smtp.close()
 
if  __name__  = =  '__main__' :
     run()
     fileName = 'out.csv'
     cmd  =  'iconv -f UTF8 -t GB18030 %s -o %s.bak && mv %s.bak %s'  % (fileName,fileName,fileName,fileName)
     os.system(cmd)
     Content =  'Dear ALL: <br> &nbsp;&nbsp; 附件内国家IP访问数据分析统计,请查收!  <br> &nbsp;&nbsp; 如有任何问题,请及时与我联系!'
     Subject  =  '[分析]国家创建数据IP分析统计'
     sendMail(html = Content,emailaddress = 'kuangl@test.com' ,mailSubject = Subject)

五、执行结果

1
2
3
4
5
utf-8
IP: 41.42.97.104 国家: 埃及 访问数: 2
IP: 99.122.189.203 国家: 美国 访问数: 3
总共有多少IP: 2
最大访问IP数: { '99.122.189.203' : 3}

六、邮件发送结果

wKioL1Tu5XmwRhZ6AACUl5-Zu80979.jpg



本文转自 kuangling 51CTO博客,原文链接:http://blog.51cto.com/kling/1615505

相关实践学习
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
相关文章
|
1月前
|
监控 安全 程序员
Python日志模块配置:从print到logging的优雅升级指南
从 `print` 到 `logging` 是 Python 开发的必经之路。`print` 调试简单却难维护,日志混乱、无法分级、缺乏上下文;而 `logging` 支持级别控制、多输出、结构化记录,助力项目可维护性升级。本文详解痛点、优势、迁移方案与最佳实践,助你构建专业日志系统,让程序“有记忆”。
203 0
|
1月前
|
Java 数据处理 索引
(Pandas)Python做数据处理必选框架之一!(二):附带案例分析;刨析DataFrame结构和其属性;学会访问具体元素;判断元素是否存在;元素求和、求标准值、方差、去重、删除、排序...
DataFrame结构 每一列都属于Series类型,不同列之间数据类型可以不一样,但同一列的值类型必须一致。 DataFrame拥有一个总的 idx记录列,该列记录了每一行的索引 在DataFrame中,若列之间的元素个数不匹配,且使用Series填充时,在DataFrame里空值会显示为NaN;当列之间元素个数不匹配,并且不使用Series填充,会报错。在指定了index 属性显示情况下,会按照index的位置进行排序,默认是 [0,1,2,3,...] 从0索引开始正序排序行。
210 0
|
4月前
|
数据采集 Web App开发 iOS开发
解决Python爬虫访问HTTPS资源时Cookie超时问题
解决Python爬虫访问HTTPS资源时Cookie超时问题
|
7月前
|
存储 监控 API
【Azure App Service】分享使用Python Code获取App Service的服务器日志记录管理配置信息
本文介绍了如何通过Python代码获取App Service中“Web服务器日志记录”的配置状态。借助`azure-mgmt-web` SDK,可通过初始化`WebSiteManagementClient`对象、调用`get_configuration`方法来查看`http_logging_enabled`的值,从而判断日志记录是否启用及存储方式(关闭、存储或文件系统)。示例代码详细展示了实现步骤,并附有执行结果与官方文档参考链接,帮助开发者快速定位和解决问题。
226 22
|
8月前
|
API 开发工具 Python
|
11月前
|
存储 应用服务中间件 开发工具
对象存储OSS-Python设置代理访问请求
通过 Python SDK 配置 nginx 代理地址请求阿里云 OSS 存储桶服务。示例代码展示了如何使用 RAM 账号进行身份验证,并通过代理下载指定对象到本地文件。
478 15
|
12月前
|
监控 数据挖掘 数据安全/隐私保护
Python脚本:自动化下载视频的日志记录
Python脚本:自动化下载视频的日志记录
|
Python
python读写操作excel日志
主要是读写操作,创建表格
161 2
|
Python Windows
python知识点100篇系列(24)- 简单强大的日志记录器loguru
【10月更文挑战第11天】Loguru 是一个功能强大的日志记录库,支持日志滚动、压缩、定时删除、高亮和告警等功能。安装简单,使用方便,可通过 `pip install loguru` 快速安装。支持将日志输出到终端或文件,并提供丰富的配置选项,如按时间或大小滚动日志、压缩日志文件等。还支持与邮件通知模块结合,实现邮件告警功能。
282 0
python知识点100篇系列(24)- 简单强大的日志记录器loguru

推荐镜像

更多