python SocketServer实现传输监控数据

2015年3月11日 发表评论 阅读评论

python利用SocketServer和multiprocessing实现传输监控数据,分为服务端和客户端,这里通过pickle模块实现数据的条带化,减少空间的占用。由于只是出于演示,这里只传uptime的值过去。

一、服务端

#!/usr/bin/env python
import multiprocessing
import os,sys
import SocketServer,time
import pickle
class MyTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        print 'got a connection from:',self.client_address[0]
        self.data = self.request.recv(1024).strip()
        if not self.data:
                print 'Client is disconnected...',self.client_address[0]
        if self.data == 'InsertData':
                print self.data
                print "going to receive date",self.data
                self.request.send('ReadyToReceiveFile')
                data = self.request.recv(4096)
                if data == 'DataSendDone':
                        print 'Transfer is done.'
                else:
                        Monitor_data = data
                        Monitor_data = pickle.loads(Monitor_data)
                        print Monitor_data
#                                mysql.InsertData(Monitor_data)
                        print "INserDatadone"
        if self.data == 'UpdateData':
                print "going to receive date",self.data
                self.request.send('ReadyToReceiveFile')
                data = self.request.recv(4096)
                print data
                if data == 'DataSendDone':
                        print 'Transfer is done.'
                else:
                        Monitor_data = data
                        Monitor_data = pickle.loads(Monitor_data)
#                                mysql.UpdateData(Monitor_data)
                        print 'updatedone......'
if __name__ == "__main__":
    HOST,PORT = "",9999
    server = SocketServer.ThreadingTCPServer((HOST, PORT), MyTCPHandler)
    jobs=[]
    for i in range(3):
            server_thread = multiprocessing.Process(target=server.serve_forever)
            server_thread.daemon = True
            jobs.append(server_thread)
            server_thread.start()
            time.sleep(1)
    for j in jobs:
            j.join()

二、客户端

#!/usr/bin/env python
# coding=utf8
import commands
import time
import os
import socket
import pickle
def get_ip():
    ip={}
    status,interface = commands.getstatusoutput("ifconfig -s|grep -v Iface|grep -v lo |awk '{print $1}'")
    inface = interface.split('\n')
    for i in range(len(inface)):
            var=inface[i]
            os.environ['var']=str(var)
            status,inter_ip=commands.getstatusoutput("ifconfig `echo $var`|sed -n 2p|awk  '{ print $2 }'|awk -F : '{ print $2 }'")
            ip[inface[i]]=inter_ip
    return ip
#if __name__ == '__main__':
MonitorData=pickle.loads(pickle.dumps(get_ip()))
#        local_file = file('/tmp/monitor_data.pickle','w')
#        pickle.dump(ip_data,local_file)
def UpTime():
    Uptime = time.strftime('%Y-%m-%d %H:%M:%S')
    return Uptime
def Write_local_data():
    try:
        local_file = file('/tmp/monitor_data.pickle','w')
        pickle.dump(MonitorData,local_file)
    except IOError:
        print "Write Error"
def check_local_data():
    try:
        local_file = file('/tmp/monitor_data.pickle')
        local_data = pickle.load(local_file)
        print local_data
    except EOFError:
        Write_local_data()
        print 'Write monitor to file'
        return False
    if MonitorData == local_data:
        Update = {}
        Update['Uptime'] = UpTime()
        return Update
    else:
        Write_local_data()
        return False
def SendMonitorData():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('192.168.0.103', 9999))
    check_data = check_local_data()
    print check_data
    if check_data is False:
        MonitorData['Uptime'] = UpTime()
        monitor_data = pickle.dumps(MonitorData)
        while True:
            s.sendall('InsertData')
            data = s.recv(1024)
            if data == 'ReadyToReceiveFile':
                s.sendall(monitor_data)
                time.sleep(30)
                s.sendall('DataSendDone')
                break
        s.close()
    else:
        monitor_data = pickle.dumps(check_data)
        print monitor_data
        while True:
            s.sendall('UpdateData')
            data = s.recv(1024)
            if data == 'ReadyToReceiveFile':
                s.sendall(monitor_data)
                time.sleep(30)
                s.sendall('DataSendDone')
                break
        s.close()
if __name__ == '__main__':
    SendMonitorData() 

三、效果

[root@flask 361way]# python server.py
got a connection from: 192.168.0.104
going to receive date UpdateData
(dp0
S'Uptime'
p1
S'2015-02-23 10:41:51'
p2
s.
updatedone......
got a connection from: 192.168.0.105
going to receive date UpdateData
(dp0
S'Uptime'
p1
S'2015-02-23 10:41:29'
p2
s.
updatedone......

这里我开了两个client端,所以服务端也会收到两台主机发来的数据。接下来可以把这些数据插入数据库,然后在前台展示,可以实现开源监控系统。




本站的发展离不开您的资助,金额随意,欢迎来赏!

You can donate through PayPal.
My paypal id: itybku@139.com
Paypal page: https://www.paypal.me/361way

  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.