设为首页 收藏本站
查看: 2479|回复: 0

[经验分享] Python基于nginx访问日志并统计IP访问量

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-2-27 08:35:15 | 显示全部楼层 |阅读模式
   如果想看看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={}
    f = 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+')
    b = '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]
        c = '%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
    g = ""
    d = '总共有多少IP:%s' %(len(ip_views))
    e = '最大访问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}



六、邮件发送结果
QQ截图20150227083502.png


运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-42715-1-1.html 上篇帖子: Bash下的实用小脚本(不定期更新) 下篇帖子: bash脚本创建临时文件以及信号捕捉 访问量 统计
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表