MonitorAgent.py:

  • 组件调用:psutil,urllib,urllib2
  • 实现功能:负责采集本机内存使用率,cpu,磁盘,网络流量

Monitorserver.py:

  • 组件调用:cgi,pymysql,json,MySQLdb
  • 实现功能:负责把我们其他服务器的采集的信息存入数据库

#_*_coding:utf-8_*_
#负责采集本机内存使用率,cpu,磁盘,网络流量
#by Linhut
#time:2017/4/7
from __future__ import division     #对future导入计算
import psutil,urllib,urllib2
class MonitorAgent(object):
    def __init__(self,url='http://127.0.0.1:8000/cgi-bin/MonitorServer.py'):    #传递数据
        self.url = url
        self.host_information = {'memory':{},'cpu':{},'disk':{},'network':{}}   #先创建一个大字典

    def memory(self):   #内存类方法
        memKeys = ['total','available','percent','used','free']         #采集内存(total总大小、available可用空间、percent使用率、used已经使用的、free还剩余的)
        memValues = psutil.virtual_memory()     #获取值
        memINfo = dict(zip(memKeys,memValues))      #把键和值组合
        memINfo = {k:str(v / pow(1024.0, 3)) + ' GB' for k, v in memINfo.items() if k !='percent'}   #先变成字符串进行拼接,并继续排除
        memINfo['percent'] = psutil.virtual_memory().percent    #再把排除的加入字典
        return memINfo      #返回memINfo更新字典

    def cpu(self):  #cpu
        cpuKeys = ['user','system','idle','interrupt','dpc']          #百分比,用户使用时间,
        cpuValues = psutil.cpu_times()
        cpuInfo = dict(zip(cpuKeys,cpuValues))
#        cpuInfo['percent'] = psutil.cpu_times()     #cpu占用百分比
        return cpuInfo

    def disk(self):     #磁盘
        diskKeys = ['read_count','write_count','read_bytes','write_bytes','read_time','write_time']
        diskValues = psutil.disk_io_counters()
        diskInfo = dict(zip(diskKeys,diskValues))
        diskInfo = {k: str(v / pow(1024.0, 3)) + ' GB' for k, v in diskInfo.items() if k != 'write_count' and 'read_count'}
        diskInfo['write_count'] = psutil.disk_io_counters().write_count
        diskInfo['read_count'] = psutil.disk_io_counters().read_count
        return diskInfo

    def network(self):  #网络
        netKeys = ['fd','family','type','laddr','raddr','status','pid']
        netValues = psutil.net_connections()
        netInfo = dict(zip(netKeys,netValues))
        return netInfo

    def send(self):
        url = self.url
        self.host_information['memory'] = self.memory()      #执行内存方法
        self.host_information['cpu'] = self.cpu()            #执行cpu方法
        self.host_information['disk'] = self.disk()          #执行磁盘方法
        self.host_information['network'] = self.network()    #执行网络方法
        self.data = urllib.urlencode(self.host_information).decode()
        self.headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3088.3 Safari/537.36'}
        req = urllib2.Request(url=self.url,data=self.data,headers=self.headers)           #data为提交的data的数据
        result = urllib2.urlopen(req).read()
        print result
        return self.host_information

if __name__ == '__main__':      #直接调用类方法
    agent = MonitorAgent()
    agent.send()
# #_*_coding:utf-8_*_
# #负责把我们其他服务器的采集的信息保存到数据库
# #by Linhut
# #time:2017/4/7
import cgi,pymysql,json,MySQLdb
form = cgi.FieldStorage()
memInfo = form['memory']

cpuInfo = form['cpu']

diskInfo = form['disk']

netInfo = form['network']

insert_memory_sql = "INSERT INTO memory(Total,Available,Paercent,Used,Free) VALUE ('%s','%s','%s','%s','%s');"%(eval(memInfo.value)['total'],eval(memInfo.value)['available'],eval(memInfo.value)['percent'],eval(memInfo.value)['used'],eval(memInfo.value)['free'])
insert_cpu_sql = "INSERT INTO memory('User',System,Idle,Interrupt,Dpc) VALUE ('%s','%s','%s','%s','%s');"%(eval(cpuInfo.value)['user'],eval(cpuInfo.value)['system'],eval(cpuInfo.value)['idle'],eval(cpuInfo.value)['interrupt'],eval(cpuInfo.value)['dpc'])
insert_disk_sql = "INSERT INTO memory(Read_count,Write_count,Read_bytes,Write_bytes,Read_time,Write_time) VALUE ('%s','%s','%s','%s','%s','%s');"%(eval(diskInfo.value)['read_count'],eval(diskInfo.value)['write_count'],eval(diskInfo.value)['read_bytes'],eval(diskInfo.value)['write_bytes'],eval(diskInfo.value)['read_time'],eval(diskInfo.value)['write_time'])
insert_monitor_sql = "INSERT INTO memory(Family,Fd,'Type',Laddr,Raddr,Status,Pid) VALUE ('%s','%s','%s','%s','%s','%s'.'%s');"%(eval(netInfo.value)['family'],eval(netInfo.value)['fd'],eval(netInfo.value)['type'],eval(netInfo.value)['laddr'],eval(netInfo.value)['raddr'],eval(netInfo.value)['status'],eval(netInfo.value)['pid'])

conn = pymysql.connect(
host='127.0.0.1',
port=719,
user='root',
passwd='root',
db='test')

cur = conn.cursor()
cur.execute(insert_memory_sql)
cur.execute(insert_cpu_sql)
cur.execute(insert_disk_sql)
cur.execute(insert_monitor_sql)
conn.commit()
conn.close()

print "Content-type:text/html"
print
print "<html>"
print "<head>"
print "<meta charset=\"utf-8\">"
print "<title>保存数据</title>"
print "</head>"
print "<body>"
print 'meminfo',memInfo
print 'cpuInfo:',cpuInfo
print 'diskInfo',diskInfo
print 'netInfo',netInfo
print "</body>"
print "</html>"