システム情報の取得

8731 ワード

1.python
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('
')[0]     def getKerner(self):         return os.popen('uname -r').readlines()[0].split('
')[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
" % 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)

2.
[root@localhost ~]# cat ./agent/mon.py
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('
')[0]     def getKerner(self):         return os.popen('uname -r').readlines()[0].split('
')[0]     def run_res(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
" % self.data)     def run(self):         mysql=Mysql('192.168.0.58','root','123456','host')         while 1:             print('------------ok')             res= mon().run_res()             ts=int(time.time())             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]             #-----------------------------------              sqls="insert into hostinfo (ip,time,cpuPercent,memTotal,memFree,diskTotal,diskFree) values('%s',%s,%s,%s,%s,%s,%s)"             mysql.cmd(sqls%(ip,ts,cpuPercent,memTotal,memFree,diskTotal,diskFree))             mysql.commit()             time.sleep(60) if __name__ == "__main__":     mon().run()

3.windos
__author__ = 'Administrator'
import os
import win32api
import win32con
import wmi
import time
import sys
sys.path.append('./')
import sql

mysql=sql.Mysql('127.0.0.1','root','123456','host')
def getSysInfo(wmiService = None):
    result = {}
    if wmiService == None:
        wmiService = wmi.WMI()
    # cpu
    for cpu in wmiService.Win32_Processor():
        timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        result['cpuPercent'] = cpu.loadPercentage
    # memory
    cs = wmiService.Win32_ComputerSystem()
    os = wmiService.Win32_OperatingSystem()
    result['memTotal'] = int(int(cs[0].TotalPhysicalMemory)/1024/1024)
    result['memFree'] = int(int(os[0].FreePhysicalMemory)/1024)
    #disk
    result['diskTotal'] = 0
    result['diskFree'] = 0
    for disk in wmiService.Win32_LogicalDisk(DriveType=3):
        result['diskTotal'] += int(disk.Size)
        result['diskFree'] += int(disk.FreeSpace)
    result['diskTotal'] = int(result['diskTotal']/1024/1024)
    result['diskFree'] = int(result['diskFree']/1024/1024)
    return result

if __name__ == '__main__':
    wmiService = wmi.WMI()
    while 1:
        #timestamp = time.strftime('%Y-%m-%d %H:%M', time.localtime())
        timestamp = int(time.time())
        cpuPercent=getSysInfo(wmiService)['cpuPercent']
        memTotal=getSysInfo(wmiService)['memTotal']
        memFree =getSysInfo(wmiService)['memFree']
        memFree= memTotal  - memFree
        diskTotal=getSysInfo(wmiService)['diskTotal']
        diskFree =getSysInfo(wmiService)['diskFree']
        try:
            sqls="insert into  `hostinfo` (ip,time,cpuPercent,memTotal,memFree,diskTotal,diskFree) values('%s',%s,%s,%s,%s,%s,%s);"%('127.0.0.1',timestamp,cpuPercent,memTotal,memFree,diskTotal,diskFree)
            mysql.cmd(sqls)
            mysql.commit()
            print('----------------------------------------------OK')
        except:
            print('----------------------------------------------Faile')
        time.sleep(60)