统计nginx日志中访客的IP和次数,并且实时写入redis中。

具体实现的代码如下:


#!/usr/bin/python
#coding=utf-8
#__author__ = 'chenhuachao'
#-------------------------------
#created by chenhuachao on 2015/7/15
#-------------------------------
import re
from time import sleep 
import redis
#iipcount = []
def get_ip():
	'''这个函数,主要是统计出日志里面的访问IP,和统计出IP出现的个数
	'''
	print "\033[31m程序每5秒正常运行一次中...\033[0m"
	print "\033[32mUse Control-C to exit\033[0m"
	iplist=[]
	log_file=open(r"/usr/local/nginx/logs/access.log","r+")
	for line in log_file:
		#print line
		#sleep (2)
		ip = re.match(r"\d+\.\d+.\d+.\d+",line)
	#	print ip.group()
		iplist.append(ip.group())
	print iplist
	ipcount=set(iplist)
#	print ipcount
	for countip in ipcount:
		count_ip=iplist.count(countip)
		print count_ip
		conn = redis.StrictRedis(host='localhost',port=6379)

	#	print iplist.count(countip),"of",countip,"in list"
		conn.hset('wiki.log-host','%s'%countip,'%s'%count_ip)
	
		
if __name__ == '__main__':
	print "\033[31m程序每5秒正常运行一次中...\033[0m"
	while True:
		try:
			sleep(5)
			get_ip()
		except KeyboardInterrupt:
			print "\033[32m 退出了。。。\033[0m"
			break	

wKioL1WlxZbjlHWLAAFWEObFghw865.jpgwKiom1Wlw72QSmCyAANVlyT9zsQ437.jpg

你可能感兴趣的:(统计nginx日志中访客的IP和次数,并且实时写入redis中。)