服務器端將獲得的ip寫入數據庫:python
#! /usr/bin/env pythonnginx
# encoding: utf-8redis
# time : 2015-06-02 9:55:24shell
# use : rpc數據庫
#在192.168.8.214創建服務器端,用函數redis_records_add在redis中處理ip服務器
import sys函數
import redisthis
reload(sys)spa
sys.setdefaultencoding('utf8')線程
from SimpleXMLRPCServer import SimpleXMLRPCServer
def redis_con(host):
r = redis.Redis(host='%s' % host, port='6379')
return r
def redis_records_add(key, value):
try:
conn = redis_con('192.168.8.214')
# 判斷 key 是否在redis中已經有值,若是有那麼自增1,若是沒有 那麼設置爲1
if conn.zscore(key, value):
redis_score = int(conn.zscore(key, value))+1
conn.zadd(key, value, redis_score)
return conn.zscore(key, value)
else:
conn.zadd(key, value, 1)
except Exception as e:
return e
server = SimpleXMLRPCServer(("192.168.8.214", 8000), allow_none=True)
print "Listening on port 8000..."
server.register_multicall_functions()
server.register_function(redis_records_add)
server.serve_forever()
客戶端腳本:
# coding:utf-8
__author__ = 'admin'
# --------------------------------
# Created by admin on 2015/5/29.
# ---------------------------------
#/usr/bin/python
import redis,re,subprocess,threading,Queue,xmlrpclib.os
host="192.168.8.137"
dir="/home/nginx/logs/"
_popen={}
queue=Queue.Queue()
#獲取/home/nginx/logs/目錄下的log文件列表
def logs_list():
list=os.listdir(dir)
log_list=[l for l in list if l.endswith(".log")]
return log_list
#獲取log的一行數據
def get_one_line(logpath):
"get one line from log,logpath mast be a str"
global _popen,state
if not _popen.has_key(logpath):
_popen[logpath]=subprocess.Popen("tail -f %s"%(logpath,),stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
a=_popen[logpath].stdout.readline()
return a
#獲取一次訪問的IP
def get_guest_ip_info(log):
"get guest ip,this fun return a string"
while 1:
info=get_one_line(log)
ip=re.match("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",info)
return ip.group()
def ip_count():
# global queue
# r = redis.Redis(host=host, port=6379, db=0)
# while 1:
# item=queue.get()
# if not r.exists(item[0]):
# r.zadd(item[0],item[1],1)
# else:
# #直接寫也能夠,不存在key值的話會自動建立
# r.zincrby(item[0],item[1],1)
global queue
while 1:
item=queue.get()
print item
proxy=xmlrpclib.ServerProxy("http://192.168.8.214:8000",allow_none=True)
proxy.redis_records_add(item[0],item[1])
def start_thread(target,args):
"start a theard"
t=threading.Thread(target=target,args=args)
#加上setDaemon(True)的話,主線程不等待子線程結束就關閉全部線程,全部在子線程裏print調試的內容都不會再前臺顯示出來
# t.setDaemon(True)
t.start()
def put_ip(log_name,log):
global queue
while 1:
ip=get_guest_ip_info(log)
queue.put([log_name,ip])
def handle():
log_list=logs_list()
for log in log_list:
redis_key=log.split(".")[0]
log_name=dir+log
#爲避免put_ip陷入死循環(while 1:)沒法執行後面的代碼,因此每一個函數都用一個線程單獨運行。
#target目標函數不能帶括號,args爲空時,用()表示,一個參數用(args,)表示
start_thread(put_ip,(redis_key,log_name))
start_thread(ip_count,())
def main():
#主線程
start_thread(handle,())
if __name__ == '__main__':
main()
#放到後臺運行ps -ef |grep python 能夠看到
#python ip_count.py &
#遠程鏈接到192.168.8.214查看
#redis-cli -h 192.168.8.214
#keys "wiki"
#ZRANGE wiki 0 -1 withscores