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

一、服务端

 1#!/usr/bin/env python
 2import multiprocessing
 3import os,sys
 4import SocketServer,time
 5import pickle
 6class MyTCPHandler(SocketServer.BaseRequestHandler):
 7    def handle(self):
 8        print 'got a connection from:',self.client_address[0]
 9        self.data = self.request.recv(1024).strip()
10        if not self.data:
11            print 'Client is disconnected...',self.client_address[0]
12        if self.data == 'InsertData':
13            print self.data
14            print "going to receive date",self.data
15            self.request.send('ReadyToReceiveFile')
16            data = self.request.recv(4096)
17            if data == 'DataSendDone':
18                print 'Transfer is done.'
19            else:
20                Monitor_data = data
21                Monitor_data = pickle.loads(Monitor_data)
22                print Monitor_data
23                mysql.InsertData(Monitor_data)
24                print "INserDatadone"
25        if self.data == 'UpdateData':
26            print "going to receive date",self.data
27            self.request.send('ReadyToReceiveFile')
28            data = self.request.recv(4096)
29            print data
30            if data == 'DataSendDone':
31                print 'Transfer is done.'
32            else:
33                Monitor_data = data
34                Monitor_data = pickle.loads(Monitor_data)
35                mysql.UpdateData(Monitor_data)
36                print 'updatedone......'
37if __name__ == "__main__":
38    HOST,PORT = "",9999
39    server = SocketServer.ThreadingTCPServer((HOST, PORT), MyTCPHandler)
40    jobs=[]
41    for i in range(3):
42            server_thread = multiprocessing.Process(target=server.serve_forever)
43            server_thread.daemon = True
44            jobs.append(server_thread)
45            server_thread.start()
46            time.sleep(1)
47    for j in jobs:
48            j.join()

二、客户端

 1#!/usr/bin/env python
 2# coding=utf8
 3import commands
 4import time
 5import os
 6import socket
 7import pickle
 8def get_ip():
 9    ip={}
10    status,interface = commands.getstatusoutput("ifconfig -s|grep -v Iface|grep -v lo |awk '{print $1}'")
11    inface = interface.split('\n')
12    for i in range(len(inface)):
13            var=inface[i]
14            os.environ['var']=str(var)
15            status,inter_ip=commands.getstatusoutput("ifconfig `echo $var`|sed -n 2p|awk  '{ print $2 }'|awk -F : '{ print $2 }'")
16            ip[inface[i]]=inter_ip
17    return ip
18#if __name__ == '__main__':
19MonitorData=pickle.loads(pickle.dumps(get_ip()))
20#        local_file = file('/tmp/monitor_data.pickle','w')
21#        pickle.dump(ip_data,local_file)
22def UpTime():
23    Uptime = time.strftime('%Y-%m-%d %H:%M:%S')
24    return Uptime
25def Write_local_data():
26    try:
27        local_file = file('/tmp/monitor_data.pickle','w')
28        pickle.dump(MonitorData,local_file)
29    except IOError:
30        print "Write Error"
31def check_local_data():
32    try:
33        local_file = file('/tmp/monitor_data.pickle')
34        local_data = pickle.load(local_file)
35        print local_data
36    except EOFError:
37        Write_local_data()
38        print 'Write monitor to file'
39        return False
40    if MonitorData == local_data:
41        Update = {}
42        Update['Uptime'] = UpTime()
43        return Update
44    else:
45        Write_local_data()
46        return False
47def SendMonitorData():
48    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
49    s.connect(('192.168.0.103', 9999))
50    check_data = check_local_data()
51    print check_data
52    if check_data is False:
53        MonitorData['Uptime'] = UpTime()
54        monitor_data = pickle.dumps(MonitorData)
55        while True:
56            s.sendall('InsertData')
57            data = s.recv(1024)
58            if data == 'ReadyToReceiveFile':
59                s.sendall(monitor_data)
60                time.sleep(30)
61                s.sendall('DataSendDone')
62                break
63        s.close()
64    else:
65        monitor_data = pickle.dumps(check_data)
66        print monitor_data
67        while True:
68            s.sendall('UpdateData')
69            data = s.recv(1024)
70            if data == 'ReadyToReceiveFile':
71                s.sendall(monitor_data)
72                time.sleep(30)
73                s.sendall('DataSendDone')
74                break
75        s.close()
76if __name__ == '__main__':
77    SendMonitorData() 

三、效果

 1[root@flask 361way]# python server.py
 2got a connection from: 192.168.0.104
 3going to receive date UpdateData
 4(dp0
 5S'Uptime'
 6p1
 7S'2015-02-23 10:41:51'
 8p2
 9s.
10updatedone......
11got a connection from: 192.168.0.105
12going to receive date UpdateData
13(dp0
14S'Uptime'
15p1
16S'2015-02-23 10:41:29'
17p2
18s.
19updatedone......

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