python 獲取Linux和Windows硬件信息

發布時間:2018-08-05 19:59:14編輯:admin閱讀(5665)

    linux


    獲取linux硬件信息的方式,有很多。

    1.使用puppet或者saltstack

    2.直接讀取/proc/xx文件,比如cpu信息,就是/proc/cpuinfo

    3.dmidecode

    4.psutil,它可以獲取某些信息,但是對于CPU型号,無法獲取!


    接下來讨論一下關于 python-hwinfo, 它是一個展示硬件信息概況的工具之一,并且其配置簡潔


    什麼是 python-hwinfo


    這是一個通過解析系統工具(例如 lspci 和 dmidecode)的輸出,來檢查硬件和設備的 Python 庫。它提供了一個簡單的命令行工具,可以用來檢查本地、遠程的主機和記錄的信息。用 sudo 運行該命令以獲得最大的信息。


    另外,你可以提供服務器 IP 或者主機名、用戶名和密碼,在遠程的服務器上執行它。當然你也可以使用這個工具查看其它工具捕獲的輸出(例如 demidecode 輸出的 dmidecode.out,/proc/cpuinfo 輸出的cpuinfo,lspci -nnm 輸出的 lspci-nnm.out)。


    Linux 上如何安裝 python-hwinfo


    在絕大多數 Linux 發行版,都可以通過 pip 包安裝。為了安裝 python-hwinfo, 确保你的系統已經有 Python 和python-pip 包作為先決條件。

    pip 是 Python 附帶的一個包管理工具,在 Linux 上安裝 Python 包的推薦工具之一。

    在 RHEL/CentOS 平台,使用 YUM 命令安裝 pip

    yum install -y python-pip python-devel


    最後,執行下面的 pip 命令安裝 python-hwinfo

    pip install python-hwinfo


    怎麼在本地機器使用 python-hwinfo


    執行下面的命令,檢查本地機器現有的硬件。輸出很清楚和整潔,這是我在其他命令中沒有看到的。


    它的輸出分為了五類:


    1.Bios Info(BIOS 信息): BIOS 供應商名稱、系統産品名稱、系統序列号、系統唯一标識符、系統制造商、BIOS 發布日期和BIOS 版本。

    2.CPU Info(CPU 信息):處理器編号、供應商 ID,CPU 系列代号、型号、步進編号、型号名稱、CPU 主頻。

    3.Ethernet Controller Info(網卡信息): 供應商名稱、供應商 ID、設備名稱、設備 ID、子供應商名稱、子供應商 ID,子設備名稱、子設備 ID。

    4.Storage Controller Info(存儲設備信息): 供應商名稱、供應商 ID、設備名稱、設備 ID、子供應商名稱,子供應商 ID、子設備名稱、子設備 ID。

    5.GPU Info(GPU 信息): 供應商名稱、供應商 ID、設備名稱、設備 ID、子供應商名稱、子供應商 ID、子設備名稱、子設備 ID。


    執行命名hwinfo -e 表示輸出json格式的數據

    [root@localhost ~]# hwinfo -e
    
    
    {
        "bios": {
            "bios_vendor_name": "Phoenix Technologies LTD",
            "system_product_name": "VMware Virtual Platform",
            "system_serial_number": "VMware-56 4d 53 d2 bd 73 ed 36-61 08 23 cc 4a c7 b7 ff",
            "chassis_type": "Other",
            "system_uuid": "564D53D2-BD73-ED36-6108-23CC4AC7B7FF",
            "system_manufacturer": "VMware, Inc.",
            "socket_count": 64,
            "bios_release_date": "05/19/2017",
            "bios_version": "6.00",
            "socket_designation": "CPU #000, CPU #001, CPU #002, CPU #003, CPU #004, CPU #005, CPU #006, CPU #007, CPU #008, CPU #009, CPU #010, CPU #011, CPU #012, CPU #013, CPU #014, CPU #015, CPU #016, CPU #017, CPU #018, CPU #019, CPU #020, CPU #021, CPU #022, CPU #023, CPU #024, CPU #025, CPU #026, CPU #027, CPU #028, CPU #029, CPU #030, CPU #031, CPU #032, CPU #033, CPU #034, CPU #035, CPU #036, CPU #037, CPU #038, CPU #039, CPU #040, CPU #041, CPU #042, CPU #043, CPU #044, CPU #045, CPU #046, CPU #047, CPU #048, CPU #049, CPU #050, CPU #051, CPU #052, CPU #053, CPU #054, CPU #055, CPU #056, CPU #057, CPU #058, CPU #059, CPU #060, CPU #061, CPU #062, CPU #063"
        },
        "storage_controllers": [
            {
                "subdevice_name": "Virtual Machine Chipset",
                "subdevice_id": "1976",
                "subvendor_id": "15ad",
                "vendor_id": "8086",
                "device_name": "82371AB/EB/MB PIIX4 IDE",
                "vendor_name": "Intel Corporation",
                "subvendor_name": "VMware",
                "class": "0101",
                "device_id": "7111"
            },
            {
                "subdevice_name": "LSI Logic Parallel SCSI Controller",
                "subdevice_id": "1976",
                "subvendor_id": "15ad",
                "vendor_id": "1000",
                "device_name": "53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI",
                "vendor_name": "LSI Logic / Symbios Logic",
                "subvendor_name": "VMware",
                "class": "0100",
                "device_id": "0030"
            }
        ],
        "cpu": [
            {
                "model": "94",
                "clflush_size": "64",
                "cpu_family": "6",
                "address_sizes": "40 bits physical, 48 bits virtual",
                "vendor_id": "GenuineIntel",
                "bogomips": "5202.00",
                "processor": "0",
                "fpu": "yes",
                "cpuid_level": "22",
                "fpu_exception": "yes",
                "stepping": "3",
                "cache_alignment": "64",
                "cache_size": "6144 KB",
                "flags": "fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon nopl xtopology tsc_reliable nonstop_tsc pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm 3dnowprefetch arat fsgsbase smep",
                "microcode": "0xbe",
                "cpu_mhz": "2599.936",
                "model_name": "Intel(R) Core(TM) i7-6700HQ CPU @ 2.60GHz",
                "wp": "yes"
            }
        ],
        "gpus": [
            {
                "subdevice_name": "SVGA II Adapter",
                "subdevice_id": "0405",
                "subvendor_id": "15ad",
                "vendor_id": "15ad",
                "device_name": "SVGA II Adapter",
                "vendor_name": "VMware",
                "subvendor_name": "VMware",
                "class": "0300",
                "device_id": "0405"
            }
        ],
        "nics": [
            {
                "subdevice_name": "PRO/1000 MT Single Port Adapter",
                "subdevice_id": "0750",
                "subvendor_id": "15ad",
                "vendor_id": "8086",
                "device_name": "82545EM Gigabit Ethernet Controller (Copper)",
                "vendor_name": "Intel Corporation",
                "subvendor_name": "VMware",
                "class": "0200",
                "device_id": "100f"
            }
        ]
    }

    注意:這個命令隻能在Python 2.7才能使用。Python 3.x執行會報錯!



    Windows


    windows不能使用hwinfo,因為hwinfo是讀取/proc/xx文件的。而windows是沒有的,所以會報錯!需要使用其他模塊來獲取

    使用下面的命令安裝2個模塊

    pip install wmi pyinstaller


    新建一個文件win_sysinfo.py,内容如下:

    #_*_coding:utf-8_*_
    
    import platform
    import win32com
    import wmi
    import os
    import json
    
    def collect():
        data = {
            'os_type': platform.system(),
            'os_release':"%s %s  %s "%( platform.release() ,platform.architecture()[0],platform.version()),
            'os_distribution': 'Microsoft',
            'asset_type':'server'
        }
    
        win32obj = Win32Info()
        data.update(win32obj.get_cpu_info())
        data.update(win32obj.get_ram_info())
        data.update(win32obj.get_server_info())
        data.update(win32obj.get_disk_info())
        data.update(win32obj.get_nic_info())
    
        # for k,v in data.items():
        #    print k,v
        return data
    
    class Win32Info(object):
        def __init__(self):
            self.wmi_obj = wmi.WMI()
            self.wmi_service_obj = win32com.client.Dispatch("WbemScripting.SWbemLocator")
            self.wmi_service_connector =self.wmi_service_obj.ConnectServer(".","root\cimv2")
    
        def get_cpu_info(self):
            data = {}
            cpu_lists = self.wmi_obj.Win32_Processor()
            cpu_core_count = 0
    
            for cpu in cpu_lists:
                cpu_core_count += cpu.NumberOfCores
                cpu_model = cpu.Name
            data["cpu_count"] = len(cpu_lists)
            data["cpu_model"] = cpu_model
            data["cpu_core_count"] =cpu_core_count
            return data
    
        def get_ram_info(self):
            data = []
            ram_collections = self.wmi_service_connector.ExecQuery("Select * from Win32_PhysicalMemory")
            for item in ram_collections:
                item_data = {}
                #print item
                mb = int(1024 * 1024)
                ram_size = int(item.Capacity) / mb
                item_data = {
                    "slot":item.DeviceLocator.strip(),
                    "capacity":ram_size,
                    "model":item.Caption,
                    "manufactory":item.Manufacturer,
                    "sn":item.SerialNumber,
                }
                data.append(item_data)
    
            return {"ram":data}
        def get_server_info(self):
            computer_info =  self.wmi_obj.Win32_ComputerSystem()[0]
            system_info =  self.wmi_obj.Win32_OperatingSystem()[0]
            data = {}
            data['manufactory'] = computer_info.Manufacturer
            data['model'] = computer_info.Model
            data['wake_up_type'] = computer_info.WakeUpType
            data['sn'] = system_info.SerialNumber
    
            return data
    
        def get_disk_info(self):
            data = []
            for disk in self.wmi_obj.Win32_DiskDrive():
                #print  disk.Model,disk.Size,disk.DeviceID,disk.Name,disk.Index,disk.SerialNumber,disk.SystemName,disk.Description
                item_data = {}
                iface_choices = ["SAS","SCSI","SATA","SSD"]
                for iface in iface_choices:
                    if iface in disk.Model:
                        item_data['iface_type']  = iface
                        break
                else:
                    item_data['iface_type']  = 'unknown'
                item_data['slot']  = disk.Index
                item_data['sn']  = disk.SerialNumber
                item_data['model']  = disk.Model
                item_data['manufactory']  = disk.Manufacturer
                item_data['capacity']  = int(disk.Size ) / (1024*1024*1024)
                data.append(item_data)
            return {'physical_disk_driver':data}
        def get_nic_info(self):
            data = []
            for nic in self.wmi_obj.Win32_NetworkAdapterConfiguration():
                if nic.MACAddress is not None:
                    item_data = {}
                    item_data['macaddress'] = nic.MACAddress
                    item_data['model'] = nic.Caption
                    item_data['name'] = nic.Index
                    if nic.IPAddress  is not None:
                        item_data['ipaddress'] = nic.IPAddress[0]
                        item_data['netmask'] = nic.IPSubnet
                    else:
                        item_data['ipaddress'] = ''
                        item_data['netmask'] = ''
                    bonding = 0
                    #print nic.MACAddress ,nic.IPAddress,nic.ServiceName,nic.Caption,nic.IPSubnet
                    #print item_data
                    data.append(item_data)
            return {'nic':data}
        
    if __name__=="__main__":
        ret = collect()
        print json.dumps(ret)

    注意:此腳本,也是Python 2.7。需要在windows上安裝Python 2.7


    打開cmd窗口,執行腳本

    python C:\Users\xiao\Desktop\win_sysinfo.py


    效果如下:blob.png

    但是dos窗口輸出的内容,不好複制,怎麼辦呢?

    将輸出重定向到桌面的info.txt文件中(不需要手動創建)

    python C:\Users\xiao\Desktop\win_sysinfo.py > C:\Users\xiao\Desktop\info.txt


    打開txt文件,複制内容

    打開在線json網頁,将内容複制進去

    http://opwh2c.caifu68174.cn


    點擊校驗,效果如下:

    {
    	"model": "Inspiron 7559",
    	"cpu_count": 1,
    	"os_release": "10 64bit  10.0.17134 ",
    	"nic": [{
    		"macaddress": "00:FF:D6:54:71:F4",
    		"model": "[00000001] TAP-Windows Adapter V9",
    		"ipaddress": "",
    		"name": 1,
    		"netmask": ""
    	}, {
    		"macaddress": "00:50:56:C0:00:01",
    		"model": "[00000002] VMware Virtual Ethernet Adapter for VMnet1",
    		"ipaddress": "192.168.233.1",
    		"name": 2,
    		"netmask": ["255.255.255.0", "64"]
    	}, {
    		"macaddress": "00:50:56:C0:00:08",
    		"model": "[00000003] VMware Virtual Ethernet Adapter for VMnet8",
    		"ipaddress": "192.168.218.1",
    		"name": 3,
    		"netmask": ["255.255.255.0", "64"]
    	}, {
    		"macaddress": "F4:8E:38:EE:0B:9F",
    		"model": "[00000004] Realtek PCIe GBE Family Controller",
    		"ipaddress": "192.168.12.151",
    		"name": 4,
    		"netmask": ["255.255.255.0", "64"]
    	}, {
    		"macaddress": "58:FB:84:62:18:0D",
    		"model": "[00000005] Intel(R) Dual Band Wireless-AC 3165",
    		"ipaddress": "",
    		"name": 5,
    		"netmask": ""
    	}, {
    		"macaddress": "58:FB:84:62:18:0E",
    		"model": "[00000006] Microsoft Wi-Fi Direct Virtual Adapter",
    		"ipaddress": "",
    		"name": 6,
    		"netmask": ""
    	}, {
    		"macaddress": "5A:FB:84:62:18:0D",
    		"model": "[00000007] Microsoft Wi-Fi Direct Virtual Adapter",
    		"ipaddress": "",
    		"name": 7,
    		"netmask": ""
    	}, {
    		"macaddress": "82:97:20:52:41:53",
    		"model": "[00000013] WAN Miniport (IP)",
    		"ipaddress": "",
    		"name": 13,
    		"netmask": ""
    	}, {
    		"macaddress": "86:9F:20:52:41:53",
    		"model": "[00000014] WAN Miniport (IPv6)",
    		"ipaddress": "",
    		"name": 14,
    		"netmask": ""
    	}, {
    		"macaddress": "88:73:20:52:41:53",
    		"model": "[00000015] WAN Miniport (Network Monitor)",
    		"ipaddress": "",
    		"name": 15,
    		"netmask": ""
    	}],
    	"ram": [{
    		"slot": "ChannelA-DIMM0",
    		"model": "物理内存",
    		"capacity": 8192,
    		"sn": "14093411",
    		"manufactory": "019800000000"
    	}, {
    		"slot": "ChannelB-DIMM0",
    		"model": "物理内存",
    		"capacity": 8192,
    		"sn": "06048420",
    		"manufactory": "019800000000"
    	}],
    	"cpu_model": "Intel(R) Core(TM) i7-6700HQ CPU @ 2.60GHz",
    	"manufactory": "Dell Inc.",
    	"physical_disk_driver": [{
    		"slot": 0,
    		"capacity": 119,
    		"manufactory": "(标準磁盤驅動器)",
    		"sn": "163363432723",
    		"model": "SanDisk Z400s M.2 2280 128GB",
    		"iface_type": "unknown"
    	}, {
    		"slot": 1,
    		"capacity": 465,
    		"manufactory": "(标準磁盤驅動器)",
    		"sn": "            SBY6P77H",
    		"model": "ST500LT012-1DG142",
    		"iface_type": "unknown"
    	}],
    	"wake_up_type": 6,
    	"sn": "00342-33067-00000-AAOEM",
    	"cpu_core_count": 4,
    	"os_type": "Windows",
    	"os_distribution": "Microsoft",
    	"asset_type": "server"
    }



關鍵字