自己有个tony6.com的服务器,上面挂着我的博客,web服务器是nginx。
由于最近一直在折腾python,所以简单写了个nginx日志分析工具,它可以分析出每个IP的点击数量和IP所在地。
1 #!/usr/bin/env pypy 2 #coding:utf8 3 import re 4 import sys 5 import urllib 6 import json 7 contents = sys.argv[1] 8 url = "http://ip.taobao.com/service/getIpInfo.php?ip=" 9 def ip_location(ip): 10 data = urllib.urlopen(url + ip).read() 11 datadict=json.loads(data) 12 for oneinfo in datadict: 13 if "code" == oneinfo: 14 if datadict[oneinfo] == 0: 15 return datadict["data"]["country"] + datadict["data"]["region"] + datadict["data"]["city"] + " " + datadict["data"]["isp"] 16 17 def NginxIpHite(logfile_path): 18 ipadd = r'.'.join([r'd{1,3}']*4) 19 re_ip = re.compile(ipadd) 20 iphitlisting = {} 21 for line in open(contents): 22 match = re_ip.match(line) 23 if match: 24 ip = match.group() 25 iphitlisting[ip] = iphitlisting.get(ip, 0) + 1 26 return iphitlisting 27 28 for k in NginxIpHite(contents): 29 dili = ip_location(k) 30 print "%s " % k,NginxIpHite(contents)[k],dili