import os,inspect,socket,time,pymysql num = 0 class Mysql: def __init__(self,host,user,password,db): self.cnn = pymysql.connect(host=host,user=user, passwd=password, db=db, charset='utf8') self.cur= self.cnn.cursor() def run(self,sql): self.cur.execute(sql) def cmd(self,sql): self.cur.execute(sql) return self.cur.fetchall() def commit(self): self.cnn.commit() def close(self): self.cur.close() self.cnn.close() class mon: def __init__(self): self.db_file='./db.json' self.data={} def getAmber(self): global num num+=1 return num def getDate(self): return time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()) def getProcess(self): return os.popen('ps -ef |wc -l').readlines()[0].split()[0] def getDisk(self): return os.popen("df -m |grep '/$'").readlines()[0].split() def getMem(self): return os.popen('free -m').readlines()[1].split()[1:4] def getSwap(self): return os.popen('free -m').readlines()[3].split()[1:] def getLoad(self): return os.popen('uptime').readlines()[0].split()[-3:] def getHost(self): return socket.gethostname() def getUser(self): return os.popen('uptime').readlines()[0].split()[3] def getRuntime(self): return os.popen('uptime').readlines()[0].split()[2] def getSystem(self): return os.popen('cat /etc/redhat-release').readlines()[0].split('/n')[0] def getKerner(self): return os.popen('uname -r').readlines()[0].split('/n')[0] def run(self): for fun in inspect.getmembers(self,predicate=inspect.ismethod): if fun[0][:3] == 'get': #print fun[1]() self.data[fun[0][3:]] = fun[1]() #print self.data return self.data #file(self.db_file,'a').write("%s/n" % self.data) time.sleep(15) if __name__ == "__main__": mysql=Mysql('192.168.0.58','root','123456','host') while 1: res= mon().run() memTotal=int(res['Mem'][0]) diskTotal=int(res['Disk'][0]) memFree=int(res['Mem'][2]) diskFree=int(res['Disk'][2]) cpuPercent=int(res['Process']) ip=os.popen("ifconfig |grep 'Bcast' |awk -F: '{print $2}'").readlines()[0].split()[0] print('-------------------',ip) ress=mysql.cmd('select * from hostinfo where ip="%s"'%ip) ress=list(ress[0]) for i in ress[3:]: lists=eval(i) print(lists) lists['data'].pop(0) lists['data'].append(eval(lists['name'])) sqls='update hostinfo set %s = "%s" where ip="%s"'%(str(lists['name']),lists,ip) mysql.cmd(sqls) mysql.commit() print('------------------------------------------------') time.sleep(30)
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/8313.html