demo.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
# author = 'yangxingsheng'
# date = 2017.11.3
 
import os, platform, re, json
 
try:
    import xmltodict
except ImportError as e:
    os.system('pip install xmltodict > /dev/null 2>&1')
    import xmltodict
 
 
def xmltojson(xmlstr):
    try:
        xmlparse = xmltodict.parse(xmlstr)
    except Exception:
        xmlparse = xmltodict.parse(xmlstr)
    jsonstr = json.dumps(xmlparse, indent=1)
    dictstr = eval('dict(%s)' % jsonstr)
    return dictstr
 
 
class HardwareInfo:
    def __init__(self, ostype):
        self.ostype = ostype
 
    def OsInfo(self):
        os_data = {}
        if self.ostype == 1:
            getosinfo = os.popen('cat /etc/redhat-release').read()
            os_data['system'] = getosinfo.strip('\n').strip('\"')
 
        if self.ostype == 0:
            getosinfo = os.popen('grep \'PRETTY_NAME\' /etc/os-release | awk -F \'=\' \'{print $NF}\'').read()
            os_data['system'] = getosinfo.strip('\n').strip('\"')
 
        return os_data
 
    def Cpu(self):
        cpu_data = {}
        getcupinfo = os.popen('lshw -xml -C cpu').read()
        cpu_metadata = xmltojson(getcupinfo)
        if type(cpu_metadata['list']['node']) is list:
            for node in cpu_metadata['list']['node']:
                try:
                    cpu_version = node['version']
                    cpu_cores = node['configuration']['setting'][0]['@value']
                    cpu_threads = node['configuration']['setting'][2]['@value']
                    cpu_physics_core = node['@id']
                    cpu_data['%s' % cpu_physics_core] = ['cpu_version:%s' % cpu_version, 'cpu_cores:%s' % cpu_cores,
                                                         'cpu_threads:%s' % cpu_threads]
                except Exception:
                    pass
        if type(cpu_metadata['list']['node']) is dict:
            try:
                cpu_version = cpu_metadata['list']['node']['version']
                cpu_cores = cpu_metadata['list']['node']['configuration']['setting'][0]['@value']
                cpu_threads = cpu_metadata['list']['node']['configuration']['setting'][2]['@value']
                cpu_physics_core = cpu_metadata['list']['node']['@id']
                cpu_data['%s' % cpu_physics_core] = ['cpu_version:%s' % cpu_version, 'cpu_cores:%s' % cpu_cores,
                                                     'cpu_threads:%s' % cpu_threads]
            except Exception:
                pass
        return cpu_data
 
    def Disk(self):
        disk_data = {}
        if "14.04" in self.OsInfo()['system']:
            if not os.path.exists('/sbin/hdparm'):
                os.system('apt-get -y install hdparm > /dev/null 2>&1')
            if not os.path.exists('/usr/bin/lsscsi'):
                os.system('apt-get -y install lsscsi > /dev/null 2>&1')
 
            getdiskinfo = os.popen('lsscsi -s').read()
            disk_metdata = getdiskinfo.splitlines()
            for disk in disk_metdata:
                diskinfo = disk.split()
                if 'LSI' in diskinfo[2]:
                    disk_scsi = diskinfo[0]
                    disk_type = diskinfo[2]
                    disk_mount = diskinfo[5]
                    disk_size = diskinfo[6]
                    disk_product = diskinfo[3]
                    disk_data[disk_scsi] = ['disk_product:%s' % disk_product, 'disk_size:%s' % disk_size,
                                            'disk_mount:%s' % disk_mount, 'disk_type:%s' % disk_type]
                else:
                    disk_scsi = diskinfo[0]
                    if 'SanDisk' in disk or 'INTEL' in disk:
                        disk_mount = diskinfo[6]
                        disk_size = diskinfo[7]
                    else:
                        disk_mount = diskinfo[5]
                        disk_size = diskinfo[6]
                    disk_product_metdata = os.popen('hdparm -i %s' % disk_mount).read()
                    disk_serial = re.findall(r'SerialNo\=(.*)', disk_product_metdata)
                    disk_model_metdata = re.findall(r'Model\=.*?\,', disk_product_metdata)
                    disk_model = disk_model_metdata[0].strip('Model=')
                    disk_product = disk_model.strip(',')
                    disk_data[disk_scsi] = ['disk_product:%s' % disk_product, 'disk_size:%s' % disk_size,
                                            'disk_mount:%s' % disk_mount, 'disk_serial:%s' % disk_serial[0]]
        else:
            getdiskinfo = os.popen('lshw -xml -c disk').read()
            disk_metdata = xmltojson(getdiskinfo)
 
            if type(disk_metdata['list']['node']) is list:
                for disk in disk_metdata['list']['node']:
                    try:
                        disk_product = disk['product']
                        disk_businfo = disk['businfo']
                        disk_logicalname = disk['logicalname']
                        disk_serial = disk['serial']
                        disk_size = int(disk['size']['#text']) / 1024 / 1024 / 1024
                        disk_data[disk_businfo] = ['disk_product:%s' % disk_product, 'disk_size:%sGB' % disk_size,
                                                   'disk_mount:%s' % disk_logicalname, 'disk_serial:%s' % disk_serial]
                    except Exception:
                        pass
            if type(disk_metdata['list']['node']) is dict:
                try:
                    disk_product = disk_metdata['list']['node']['product']
                    disk_businfo = disk_metdata['list']['node']['businfo']
                    disk_logicalname = disk_metdata['list']['node']['logicalname']
                    disk_serial = disk_metdata['list']['node']['serial']
                    disk_size = int(disk_metdata['list']['node']['size']['#text']) / 1024 / 1024 / 1024
                    disk_data[disk_businfo] = ['disk_product:%s' % disk_product, 'disk_size:%sGB' % disk_size,
                                               'disk_mount:%s' % disk_logicalname, 'disk_serial:%s' % disk_serial]
                except Exception:
                    pass
        return disk_data
 
    def Memory(self):
        tmp_mem_data = {}
        mem_data = {}
        get_mem_info = os.popen('lshw -xml -C Memory').read()
        mem_metadata = xmltojson(get_mem_info)
        Free_slots = 0
        Total_slots = 0
        for mems in mem_metadata['list']['node']:
            if "memory" in mems['@id']:
                try:
                    for mem in mems['node']:
                        try:
                            if 'empty' in mem['description']:
                                Free_slots = Free_slots + 1
                                Total_slots = Total_slots + 1
                                continue
                            else:
                                mem_description = mem['description']
                                mem_size = int(mem['size']['#text']) / 1024 / 1024 / 1024
                                mem_product = mem['product']
                                tmp_mem_data['%s' % mem["@id"]] = ['mem_description:%s' % mem_description,
                                                                   'mem_size:%sG' % mem_size,
                                                                   'mem_product:%s' % mem_product,
                                                                   'mem_serial:%s' % mem['serial']]
                                Total_slots = Total_slots + 1
                        except Exception as a:
                            pass
                    mem_data['%s' % mems["@id"]] = tmp_mem_data
                except Exception:
                    pass
        mem_data['Free_slots'] = Free_slots
        mem_data['Total_slots'] = Total_slots
        get_mem_num = os.popen('dmidecode -t memory').read()
        pattern = r'Maximum Capacity:\ (.*)'
        slots_mem_num = re.findall(pattern, get_mem_num)
        if 'GB' in slots_mem_num[0]:
            total_maximum_size = int(slots_mem_num[0].strip('GB')) * len(slots_mem_num)
            slots_maximum_size = total_maximum_size / Total_slots
            mem_data['total_maximum_size'] = '%dGB' % total_maximum_size
            mem_data['slots_maximum_size'] = '%dGB' % slots_maximum_size
        elif 'TB' in slots_mem_num[0]:
            total_maximum_size = int(slots_mem_num[0].strip('TB')) * len(slots_mem_num) * 1024
            slots_maximum_size = total_maximum_size / Total_slots
            mem_data['total_maximum_size'] = '%dGB' % total_maximum_size
            mem_data['slots_maximum_size'] = '%dGB' % slots_maximum_size
        return mem_data
 
    def Network(self):
        network_data = {}
        get_net_info = os.popen('lshw -xml -C network').read()
        net_metadata = xmltojson(get_net_info)
        for net in net_metadata['list']['node']:
            if "veth" in net['logicalname'] or "ifb" in net['logicalname'] or "br" in net['logicalname']:
                pass
            elif "docker" in net['logicalname']:
                network_data['%s' % net['logicalname']] = []
                network_data['%s' % net['logicalname']].append('MAC:%s' % net['serial'])
                for netset in net['configuration']['setting']:
                    try:
                        if netset['@id'] == 'link' or netset['@id'] == 'ip' or netset['@id'] == 'speed':
                            network_data['%s' % net['logicalname']].append('%s:%s' % (netset['@id'], netset['@value']))
                    except Exception:
                        pass
            else:
                network_data['%s' % net['logicalname']] = []
                network_data['%s' % net['logicalname']].append('MAC:%s' % net['serial'])
                network_data['%s' % net['logicalname']].append('product:%s' % net['product'])
                for netset in net['configuration']['setting']:
                    try:
                        if netset['@id'] == 'link' or netset['@id'] == 'ip' or netset['@id'] == 'speed':
                            network_data['%s' % net['logicalname']].append('%s:%s' % (netset['@id'], netset['@value']))
                    except Exception:
                        pass
        try:
            get_ipmi_info = os.popen('ipmitool lan print 2>/dev/null').read()
            ipmi_ip = re.findall(r'IP Address\ +:\ (.*)', get_ipmi_info)
            network_data['IPMI'] = ipmi_ip[0]
        except Exception:
            try:
                os.popen('modprobe ipmi_devintf')
                os.popen('modprobe ipmi_si')
                get_ipmi_info = os.popen('ipmitool lan print').read()
                ipmi_ip = re.findall(r'IP Address\ +:\ (.*)', get_ipmi_info)
                network_data['IPMI'] = ipmi_ip[0]
            except Exception:
                pass
 
        if "Ubuntu" in self.OsInfo()['system']:
            ip_metdata = os.popen('cat /etc/network/interfaces').read()
            if "bridge_ports" in ip_metdata:
                ips_metdata = re.findall(r'auto\ (docker.*)', ip_metdata)
                bridge_net = re.findall(r'bridge_ports\ (.*)', ip_metdata)
                get_ip_metdata = re.findall(r'addr:(.*)\  Bcast', os.popen('ifconfig %s' % ips_metdata[0]).read())
                get_mac_metdata = re.findall(r'HWaddr\ (.*)', os.popen('ifconfig %s' % ips_metdata[0]).read())
                network_data[ips_metdata[0]] = []
                network_data[ips_metdata[0]].append('ip:%s' % get_ip_metdata[0])
                network_data[ips_metdata[0]].append('MAC:%s' % get_mac_metdata[0].strip('\ '))
                network_data[ips_metdata[0]].append('bridge:%s' % bridge_net[0])
 
        return network_data
 
    def Mainboard(self):
        board_data = {}
 
        if 'Dell Inc.' in re.findall(r'Manufacturer:\ (.*)',
                                     os.popen('dmidecode | grep -A 2 "System Information"').read()):
            get_product_metdata = os.popen('dmidecode | grep -A 4 "System Information"').read()
            manufacturer = re.findall(r'Manufacturer:\ (.*)', get_product_metdata)
            ProductName = re.findall(r'Product Name:\ (.*)', get_product_metdata)
            SerialNumber = re.findall(r'Serial Number:\ (.*)', get_product_metdata)
        else:
            get_board = os.popen('dmidecode -t baseboard').read()
            manufacturer = re.findall(r'Manufacturer:\ (.*)', get_board)
            ProductName = re.findall(r'Product Name:\ (.*)', get_board)
            SerialNumber = re.findall(r'Serial Number:\ (.*)', get_board)
 
        get_power = os.popen('lshw -xml -C power').read()
        power_metadata = xmltojson(get_power)
        PowerNumber = 0
        if type(power_metadata['list']['node']) is dict:
 
            for powerk, powerv in power_metadata['list']['node'].items():
                if powerk == 'physid':
                    PowerNumber = PowerNumber + 1
        if type(power_metadata['list']['node']) is list:
            for power in power_metadata['list']['node']:
                for k, v in power.items():
                    if k == 'physid':
                        PowerNumber = PowerNumber + 1
 
        board_data['%s' % SerialNumber[0]] = ['%s %s' % (manufacturer[0], ProductName[0]),
                                              'PowerNumber:%d' % PowerNumber]
        return board_data
 
 
if __name__ == '__main__':
 
    if 'root' in os.environ.get('USER'):
        if "Ubuntu" in platform.platform():
            if not os.path.exists('/usr/bin/lshw'):
                os.system('apt-get -y install lshw > /dev/null 2>&1')
            if not os.path.exists('/usr/bin/pip'):
                os.system('apt-get -y install python-dev python-pip > /dev/null 2>&1')
            if not os.path.exists('/usr/bin/ipmitool'):
                os.system('apt-get -y install ipmitool > /dev/null 2>&1')
 
            ostype = 0
        if "centos" in platform.platform():
            if not os.path.exists('/sbin/lshw'):
                os.system('yum -q -y install lshw > /dev/null 2>&1')
            if not os.path.exists('/bin/pip'):
                os.system('yum -q -y install python-devel python-pip > /dev/null 2>&1')
            if not os.path.exists('/bin/ipmitool'):
                os.system('yum -q -y install ipmitool > /dev/null 2>&1')
 
            ostype = 1
 
        HHI = HardwareInfo(ostype)
        HostHardwareInfo = {}
        HostHardwareInfo_metdata = {}
        hostname = os.popen('cat /etc/hostname').read()
        HostHardwareInfo_metdata['OS'] = HHI.OsInfo()
        HostHardwareInfo_metdata['CPU'] = HHI.Cpu()
        HostHardwareInfo_metdata['Disk'] = HHI.Disk()
        HostHardwareInfo_metdata['Memory'] = HHI.Memory()
        HostHardwareInfo_metdata['Network'] = HHI.Network()
        HostHardwareInfo_metdata['Baseboard'] = HHI.Mainboard()
        HostHardwareInfo['%s' % hostname.strip('\n')] = HostHardwareInfo_metdata
        print HostHardwareInfo
 
    else:
        print "You Should Run This Program As Super-user(root)!"
  • python/demo.py.txt
  • 最后更改: 2019/04/16 18:31
  • (外部编辑)