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

简介:

   如果想看看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实时生图绘板
相关文章
|
11月前
|
存储 监控 算法
防止员工泄密软件中文件访问日志管理的 Go 语言 B + 树算法
B+树凭借高效范围查询与稳定插入删除性能,为防止员工泄密软件提供高响应、可追溯的日志管理方案,显著提升海量文件操作日志的存储与检索效率。
340 2
|
数据可视化 关系型数据库 MySQL
ELK实现nginx、mysql、http的日志可视化实验
通过本文的步骤,你可以成功配置ELK(Elasticsearch, Logstash, Kibana)来实现nginx、mysql和http日志的可视化。通过Kibana,你可以直观地查看和分析日志数据,从而更好地监控和管理系统。希望这些步骤能帮助你在实际项目中有效地利用ELK来处理日志数据。
1058 90
|
数据采集 机器学习/深度学习 Web App开发
Python爬虫如何应对贝壳网的IP封禁与人机验证?
Python爬虫如何应对贝壳网的IP封禁与人机验证?
|
数据采集 机器学习/深度学习 边缘计算
Python爬虫动态IP代理报错全解析:从问题定位到实战优化
本文详解爬虫代理设置常见报错场景及解决方案,涵盖IP失效、403封禁、性能瓶颈等问题,提供动态IP代理的12种核心处理方案及完整代码实现,助力提升爬虫系统稳定性。
662 0
|
域名解析 应用服务中间件 网络安全
阿里云个人博客外网访问中断应急指南:从安全组到日志的七步排查法
1. 检查安全组配置:确认阿里云安全组已开放HTTP/HTTPS端口,添加规则允许目标端口(如80/443),授权对象设为`0.0.0.0/0`。 2. 本地防火墙设置:确保服务器防火墙未阻止外部流量,Windows启用入站规则,Linux检查iptables或临时关闭防火墙测试。 3. 验证Web服务状态:检查Apache/Nginx/IIS是否运行并监听所有IP,使用命令行工具确认监听状态。 4. 测试网络连通性:使用外部工具和内网工具测试服务器端口是否开放,排除本地可访问但外网不可的问题。 5. 排查DNS解析:确认域名A记录指向正确公网IP,使用`ping/nslookup`验证解析正
770 2
|
监控 应用服务中间件 定位技术
要统计Nginx的客户端IP,可以通过分析Nginx的访问日志文件来实现
要统计Nginx的客户端IP,可以通过分析Nginx的访问日志文件来实现
1660 3
|
安全 Python
Python脚本实现IP按段分类
【10月更文挑战第04天】
351 7
|
iOS开发 MacOS Python
Python编程小案例—利用flask查询本机IP归属并输出网页图片
Python编程小案例—利用flask查询本机IP归属并输出网页图片
342 1
|
设计模式 SQL 安全
PHP中的设计模式:单例模式的深入探索与实践在PHP的编程实践中,设计模式是解决常见软件设计问题的最佳实践。单例模式作为设计模式中的一种,确保一个类只有一个实例,并提供全局访问点,广泛应用于配置管理、日志记录和测试框架等场景。本文将深入探讨单例模式的原理、实现方式及其在PHP中的应用,帮助开发者更好地理解和运用这一设计模式。
在PHP开发中,单例模式通过确保类仅有一个实例并提供一个全局访问点,有效管理和访问共享资源。本文详细介绍了单例模式的概念、PHP实现方式及应用场景,并通过具体代码示例展示如何在PHP中实现单例模式以及如何在实际项目中正确使用它来优化代码结构和性能。
394 2
|
应用服务中间件 nginx
nginx error日志 client intended to send too large body: 1434541 bytes 如何处理?
【8月更文挑战第27天】nginx error日志 client intended to send too large body: 1434541 bytes 如何处理?
1204 6

推荐镜像

更多