博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
服务器监控客户端系统状态2.0
阅读量:6340 次
发布时间:2019-06-22

本文共 3810 字,大约阅读时间需要 12 分钟。

要求:

1、客户端收集系统CPU及内存占用率,正在运行的进程名称,周期上传至服务器

2、服务器接受信息,存储至数据库

 

客户端程序:

环境:win7,python,python的psutil库

程序:

#! /usr/bin/env python#coding=utf-8'''version:2.0监控windows信息:CPU占有率,内存占有率,当前进程名称数据格式:{'name':p.name(),'memeory':p.memory_percent()},{},...]'''import socketimport timeimport psutilimport json#function of Run Server def runServer(s,HOST,PORT):    s.connect((HOST, PORT))    print 'connect success!'#function of Close Serverdef closeServer(s):    time.sleep(5)    s.close()#function of Get CPU State  def getCPUstate(interval=1):    return (str(psutil.cpu_percent(interval)) + "%")#function of Get Memory  def getMemorystate():    mem_rate = 0    for pnum in psutil.pids():        p = psutil.Process(pnum)         mem_rate = mem_rate + p.memory_percent()    return "%.2f%%"%mem_rate#function of get process's namedef getProcessName():    ProcessNameList = []    for pnum in psutil.pids():        p = psutil.Process(pnum)         ProcessNameList.append(p.name())    return ProcessNameList#function of Package Massagedef packMassage():    massage = {
'CPUstate':getCPUstate(),'Memorystate':getMemorystate(),'ProcessName':getProcessName()} print massage return massage #function of Send Massagedef sendMassage(s): s.send(json.dumps(packMassage())) time.sleep(5) s.sendall('\n')#function of Receive Massagedef recvMassage(s): data = s.recv(1024) print 'Received', repr(data)if __name__ == "__main__" : HOST = '172.29.153.22' # The server host PORT = 8000 # The same port as used by the server cycle = 60 # The cycle of sending massage while True: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) runServer(s,HOST,PORT) sendMassage(s) closeServer(s) time.sleep(cycle)

 

服务器程序:

环境:ubuntu14.04,python,tornado,mongodb

程序:

#! /usr/bin/env python#coding=utf-8  from tornado.tcpserver import TCPServer  from tornado.ioloop  import IOLoop import pymongo import json  class Connection(object):      clients = set()      def __init__(self, stream, address):         Connection.clients.add(self)         self._stream = stream          self._address = address          self._stream.set_close_callback(self.on_close)          self.read_message()      def read_message(self):          self._stream.read_until('\n', self.broadcast_messages)  #Read massage until '\n'      def broadcast_messages(self, data, massageDict):          massageDict=eval(data[:-1])     #str to dict        if 'CPUstate' in massageDict.keys() :            print '\n','CPUstate:',massageDict['CPUstate'],'\n'        if 'Memorystate' in massageDict.keys() :            print 'Memorystate:',massageDict['Memorystate'],'\n'        if 'ProcessName' in massageDict.keys() :            print 'ProcessName:',massageDict['ProcessName'],'\n'        self.storeMassage()        for conn in Connection.clients:              conn.send_message(data)        self.read_message()              def storeMassage(self,massageDict ):        conn = pymongo.Connection("localhost", 27017)        db = conn['networkSecurity']        processInfo=db['processInfo']        processInfo.insert(massageDict)        print 'success to store the massage!'          def send_message(self, data):          self._stream.write(data)               def on_close(self):          print "A user has left the chat room.", self._address        Connection.clients.remove(self)    class ChatServer(TCPServer):      def handle_stream(self, stream, address):         print "New connection :", address         Connection(stream, address)         # print "connection num is:", len(Connection.clients)  if __name__ == '__main__':      print "Server start ......"      server = ChatServer()      server.listen(8000)      IOLoop.instance().start()

 

转载于:https://www.cnblogs.com/myblog-lyc/p/4850936.html

你可能感兴趣的文章
winform datagridview 通过弹出小窗口来隐藏列 和冻结窗口
查看>>
Jquery闪烁提示特效
查看>>
最佳6款用于移动网站开发的 jQuery 图片滑块插件
查看>>
C++ String
查看>>
获取系统托盘图标的坐标及文本
查看>>
log4j Test
查看>>
HDU 1255 覆盖的面积(矩形面积交)
查看>>
SQL数据库无法附加,提示 MDF" 已压缩,但未驻留在只读数据库或文件组中。必须将此文件解压缩。...
查看>>
第二十一章流 3用cin输入
查看>>
在workflow中,无法为实例 ID“...”传递接口类型“...”上的事件“...” 问题的解决方法。...
查看>>
获取SQL数据库中的数据库名、所有表名、所有字段名、列描述
查看>>
Orchard 视频资料
查看>>
简述:预处理、编译、汇编、链接
查看>>
调试网页PAIP HTML的调试与分析工具
查看>>
路径工程OpenCV依赖文件路径自动添加方法
查看>>
玩转SSRS第七篇---报表订阅
查看>>
WinCE API
查看>>
SQL语言基础
查看>>
对事件处理的错误使用
查看>>
最大熵模型(二)朗格朗日函数
查看>>