• 代码示例
# -*- coding: UTF-8 -*-
#!/usr/bin/env python

import time,math,socket,struct
import MySQLdb,psutil

###### 内存信息 #######
def getMemoryState():
    phymem = psutil.virtual_memory()
    total = long(phymem.total)
    used = long(phymem.used)
    # percent = phymem.percent
    # mem_str = "Total:"+ str(total/1024/1024) + "MB;Used:" + str(used/1024/1024) +"MB;Percent:" + str(percent) +"%"
    mem_list =[total/1024/1024,used/1024/1024]
    return mem_list

###### CPU信息 #######
def getCpuState(interval=1):
    cpu_util = psutil.cpu_percent(interval)
    return int(cpu_util)

###### 硬盘信息 #######
def getDiskState():
    disk_total = 0
    disk_used = 0
    disk_free = 0
    disk_list = psutil.disk_partitions()
    # disk_info_list = [] # 硬盘所有信息包含挂载点
    for disk_part in disk_list:
        disk_sub_total = long(math.ceil(psutil.disk_usage(disk_part.mountpoint).total))  # 获取分区总容量
        disk_sub_used =  long(math.ceil(psutil.disk_usage(disk_part.mountpoint).used))   # 获取分区已使用
        disk_sub_free = long(math.ceil(psutil.disk_usage(disk_part.mountpoint).free))    # 获取分区剩余
        disk_sub_percent = str((math.ceil(psutil.disk_usage(disk_part.mountpoint).percent)))
        disk_sub_info = "point:" + disk_part.mountpoint + ";total:"+ str(disk_sub_total/1024/1024/1024) + "GB;used:" + str(disk_sub_used/1024/1024/1024) + "GB;free:" + str(disk_sub_free/1024/1024/1024) + "GB;percent:" + disk_sub_percent + "%"
        disk_total = disk_total + disk_sub_total
        disk_used = disk_used + disk_sub_used
        disk_free = disk_free + disk_sub_free
        # disk_info_list.append(disk_sub_info)
    # disk_percent = str(round(float(disk_used)/float(disk_total)*100,2))
    # disk_info = "Total:" + str(disk_total/1024/1024/1024) + "GB;Used:" + str(disk_used/1024/1024/1024) + "GB;Free:" + str(disk_free/1024/1024/1024) + "GB;Percent:" + disk_percent + "%"
    # disk_info_list.append(disk_info)
    disk_info = [disk_total/1024/1024/1024,disk_used/1024/1024/1024]
    return disk_info

###### 网络信息 #######
def getNetState():
    key_info, net_in, net_out = getNetDate(get_key)
    net_list = []
    received = 0
    send = 0
    for key in key_info:
        i = unicode(key, errors='ignore')
        if i !="lo" and ("Loopback" not in i):
            # j = i + ";received:" + str(net_in.get(key)) + "MB;send:" + str(net_out.get(key)) + "MB"
            # net_str = net_str + "  " + j
            received = received + net_in.get(key)
            send = send + net_out.get(key)
    net_list.append(received)
    net_list.append(send)
    return net_list

def getNetDate(func):
    key_info, old_recv, old_sent = func()  # 上一秒收集的数据
    time.sleep(1)
    key_info, now_recv, now_sent = func()  # 当前所收集的数据
    net_in = {}
    net_out = {}
    for key in key_info:
        net_in.setdefault(key, (now_recv.get(key) - old_recv.get(key)) / 1024 /1024)   # 每秒接收速率
        net_out.setdefault(key, (now_sent.get(key) - old_sent.get(key)) / 1024 /1024)  # 每秒发送速率
    return key_info, net_in, net_out

def get_key():
    # 获取网卡名称、收发字节
    key_info = psutil.net_io_counters(pernic=True).keys()  # 获取网卡名称
    recv = {}
    sent = {}
    for key in key_info:
        recv.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_recv)  # 各网卡接收的字节数
        sent.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_sent)  # 各网卡发送的字节数
    return key_info, recv, sent

###### 获取主机名和IP地址 #######
def get_ip_host():
    lis = []
    hostname = socket.gethostname()
    # ip = socket.gethostbyname(hostname)
    lis.append(hostname)
    # lis.append(ip)
    info = psutil.net_if_addrs()
    for k,v in info.items():
        for item in v:
            if item[0] == 2 and not item[1] == '127.0.0.1':
                lis.append(item[1])
    return lis


###### 执行数据库操作 #######
def mysql_sh(ip_host,machine_info):
    ### 数据初始化
    ip = socket.ntohl(struct.unpack("I", socket.inet_aton(str(ip_host[1])))[0])
    # if ip_host[2]:
    #     print("second ip is %s"% ip_host[2])
    sql_search = "select * from machine where ip='" + str(ip) + "'"
    machine_info_search = "select id from machine where ip='" + str(ip) + "'"
    # 打开数据库连接
    db = MySQLdb.connect("itopdb.southbaytech.co", "itop", "itop", "itop",3304,charset='utf8')
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    # 查询插入machine_info
    cursor.execute(sql_search)
    results = cursor.fetchall()
    if results:
        cursor.execute(machine_info_search)
        server_search = cursor.fetchall()
        for j in server_search:
            machine_id = j[0]
        # 设定machine_info插入
        disk_total = machine_info['disk_state'][0]
        disk_used = machine_info['disk_state'][1]
        mem_total = machine_info['mem_state'][0]
        mem_used = machine_info['mem_state'][1]
        net_received = machine_info['net_state'][0]
        net_send = machine_info['net_state'][1]
        create_time = int(time.time())
        machine_info_insert = 'insert into machine_info(machine_id,cpu_state,disk_total,disk_used,mem_total,mem_used,create_time,net_received,net_send) \
            values (%d,%f,%d,%d,%d,%d,%d,%d,%d)' % \
            (machine_id ,machine_info['cpu_state'],disk_total,disk_used,mem_total,mem_used,create_time,net_received,net_send)
        # 执行server_info插入
        try:
            cursor.execute(machine_info_insert)
            db.commit()
        except:
            db.rollback()
    else:
        print("machine is not exist!")
    # 关闭数据库连接
    db.close()


###### 主程序 #######
if __name__=='__main__':
    while 1 :
        try:
            machine_info = {}
            machine_info["cpu_state"] = getCpuState()
            machine_info["disk_state"] = getDiskState()
            machine_info["mem_state"] = getMemoryState()
            machine_info["net_state"] = getNetState()
            ip_host = get_ip_host()  # 获取主机名和IP地址
            mysql_sh(ip_host,machine_info)  # 数据库插入更新
            time.sleep(3)
        except KeyboardInterrupt:
            exit()