python基于nginx访问日志统计客户端ip访问量
比如,服务器上有nginx的log如下:
221.221.155.54 - - [02/Aug/2014:15:16:11 +0800] "GET / HTTP/1.1" 200 8482 "http://www.zuidaima.com/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36" "-" "0.020"
221.221.155.53 - - [02/Aug/2014:15:16:11 +0800] "GET / HTTP/1.1" 200 8482 "http://www.zuidaima.com/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36" "-" "0.020"
221.221.155.54 - - [02/Aug/2014:15:16:11 +0800] "GET / HTTP/1.1" 200 8482 "http://www.zuidaima.com/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36" "-" "0.020"
统计脚本如下:
stat_ip.py
#encoding=utf8import re
zuidaima_nginx_log_path="/usr/local/nginx/logs/www.zuidaima.com.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(zuidaima_nginx_log_path)
max_ip_view={}
for ip in ip_views:
views=ip_views[ip]
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, ",views:", views
#总共有多少ip
print "total:", len(ip_views)
#最大访问的ip
print "max_ip_view:", max_ip_view
run()
运行结果如下:
ip: 221.221.155.53 ,views: 1
ip: 221.221.155.54 ,views: 2
total: 2
max_ip_view: {'221.221.155.54': 2}
这样得到了所有ip的访问量及其最大ip的访问。
以上就介绍了python基于nginx访问日志统计客户端ip访问量,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。