WMI (Windows Management Instrumentation) 子產品可用于擷取 Windows 内部資訊,在使用Python擷取Windows系統上的相關的資訊可以使用WMI接口來擷取,
什麼是wmi?
WMI是一項核心的Windows管理技術,WMI作為一種規範和基礎結構,通過它可以通路、配置、管理和監視幾乎所有的Windows資源,比如使用者可以在遠端計算機器上啟動一個程序;設定一個在特定日期和時間運作的程序;遠端啟動計算機;獲得本地或遠端計算機的已安裝程式清單;查詢本地或遠端計算機的Windows事件日志等等。
該子產品需要 win32com 的支援,環境安裝如下,
pip install wmi
pip install pypiwin32
測試安裝結果
>>> import win32con
>>> import wmi
導入子產品沒有報錯,證明安裝完成
wmi.WMI() 用于生成wmi執行個體
>>> wmi.WMI()
<_wmi_namespace: <COMObject winmgmts:>>
查詢CPU資訊
用于擷取CPU處理器資訊對象,并存以清單形式
wmi.Win32_Processor() 方法
傳回參數: processorList
processorList: list類型,list中每個元素均為一個含cpu資訊的object對象
import wmi
w = wmi.WMI()
cpu_list = w.Win32_Processor()
print(cpu_list)
# [<_wmi_object: b'\\\\QH-20181120YSCF\\root\\cimv2:Win32_Processor.DeviceID="CPU0"'>]
import wmi
w = wmi.WMI()
cpu_list = w.Win32_Processor()
for cpu in cpu_list:
print(cpu)
instance of Win32_Processor
{
AddressWidth = 64;
Architecture = 9;
Availability = 3;
Caption = "Intel64 Family 6 Model 69 Stepping 1";
CpuStatus = 1;
CreationClassName = "Win32_Processor";
CurrentClockSpeed = 1587;
CurrentVoltage = 7;
DataWidth = 64;
Description = "Intel64 Family 6 Model 69 Stepping 1";
DeviceID = "CPU0";
ExtClock = 100;
Family = 205;
L2CacheSize = 256;
L3CacheSize = 3072;
L3CacheSpeed = 0;
Level = 6;
LoadPercentage = 32;
Manufacturer = "GenuineIntel";
MaxClockSpeed = 2301;
Name = "Intel(R) Core(TM) i5-4200U CPU @ 1.60GHz";
NumberOfCores = 2;
NumberOfLogicalProcessors = 4;
PowerManagementSupported = FALSE;
ProcessorId = "BFEBFBFF00040651";
ProcessorType = 3;
Revision = 17665;
Role = "CPU";
SocketDesignation = "CPU Socket - U3E1";
Status = "OK";
StatusInfo = 3;
SystemCreationClassName = "Win32_ComputerSystem";
SystemName = "QH-20181120YSCF";
UpgradeMethod = 33;
Version = "";
};
cpu.Name 是cpu的型号
cpu.NumberOfCores 是cpu的核心數
import wmi
w = wmi.WMI()
cpu_list = w.Win32_Processor()
for cpu in cpu_list:
print("cpu核心數",cpu.NumberOfCores)
print("cpu型号",cpu.Name)
''''
cpu核心數 2
cpu型号 Intel(R) Core(TM) i5-4200U CPU @ 1.60GHz
'''
len(cpu_list) 統計清單裡面cpu個數 cpu_count
import wmi
w = wmi.WMI()
cpu_list = w.Win32_Processor()
# 統計清單cpu個數
print(len(cpu_list))
# 一個CPU
# 1
wmi.Win32_ComputerSystem() 方法
通過Win32_ComputerSystem()方法 可以擷取機器的 制造商Manufacturer , 機器型号
import wmi
w = wmi.WMI()
obj = w.Win32_ComputerSystem()[0]
print(obj)
instance of Win32_ComputerSystem
{
AdminPasswordStatus = 3;
AutomaticManagedPagefile = TRUE;
AutomaticResetBootOption = TRUE;
AutomaticResetCapability = TRUE;
BootOptionOnLimit = 3;
BootOptionOnWatchDog = 3;
BootROMSupported = TRUE;
BootupState = "Normal boot";
Caption = "QH-20181120YSCF";
ChassisBootupState = 3;
CreationClassName = "Win32_ComputerSystem";
CurrentTimeZone = 480;
Description = "AT/AT COMPATIBLE";
DNSHostName = "QH-20181120YSCF";
Domain = "WORKGROUP";
DomainRole = 0;
EnableDaylightSavingsTime = TRUE;
FrontPanelResetStatus = 3;
InfraredSupported = FALSE;
KeyboardPasswordStatus = 3;
Manufacturer = "Dell Inc.";
Model = "Inspiron 5439";
Name = "QH-20181120YSCF";
NetworkServerModeEnabled = TRUE;
NumberOfLogicalProcessors = 4;
NumberOfProcessors = 1;
OEMStringArray = {"Dell System", "1[0638]", "3[1.3]", "4[0001]", "6[D0, D4, D8, DA, DE]", "10[A04]", "8[]", "9[]", "10[XXX]", "13[PP36S]", "14[3]", "15[9]", "16[]"};
PartOfDomain = FALSE;
PauseAfterReset = "3932100000";
PCSystemType = 2;
PowerOnPasswordStatus = 3;
PowerState = 0;
PowerSupplyState = 3;
PrimaryOwnerName = "PC";
ResetCapability = 1;
ResetCount = -1;
ResetLimit = -1;
Roles = {"LM_Workstation", "LM_Server", "NT", "Potential_Browser"};
Status = "OK";
SystemType = "x64-based PC";
ThermalState = 3;
TotalPhysicalMemory = "4198264832";
UserName = "QH-20181120YSCF\\Administrator";
WakeUpType = 6;
Workgroup = "WORKGROUP";
};
import wmi
w = wmi.WMI()
obj = w.Win32_ComputerSystem()[0]
print("機器型号",obj.model)
print("制造商",obj.Manufacturer)
'''
機器型号 Inspiron 5439
制造商 Dell Inc.
'''
wmi.Win32_OperatingSystem() 方法
可以使用 Win32_OperatingSystem() 擷取sn号 SerialNumber
import wmi
w = wmi.WMI()
obj = w.Win32_ComputerSystem()[0]
print(obj)
instance of Win32_OperatingSystem
{
BootDevice = "\\Device\\HarddiskVolume1";
BuildNumber = "7601";
BuildType = "Multiprocessor Free";
Caption = "Microsoft Windows 7 旗艦版 ";
CodeSet = "936";
CountryCode = "86";
CreationClassName = "Win32_OperatingSystem";
CSCreationClassName = "Win32_ComputerSystem";
CSDVersion = "Service Pack 1";
CSName = "QH-20181120YSCF";
CurrentTimeZone = 480;
DataExecutionPrevention_32BitApplications = TRUE;
DataExecutionPrevention_Available = TRUE;
DataExecutionPrevention_Drivers = TRUE;
DataExecutionPrevention_SupportPolicy = 2;
Debug = FALSE;
Description = "";
Distributed = FALSE;
EncryptionLevel = 256;
ForegroundApplicationBoost = 2;
FreePhysicalMemory = "431452";
FreeSpaceInPagingFiles = "2710880";
FreeVirtualMemory = "2671984";
InstallDate = "20181120154345.000000+480";
LastBootUpTime = "20190221005145.164410+480";
LocalDateTime = "20190309002538.760000+480";
Locale = "0804";
Manufacturer = "Microsoft Corporation";
MaxNumberOfProcesses = 4294967295;
MaxProcessMemorySize = "8589934464";
MUILanguages = {"zh-CN"};
Name = "Microsoft Windows 7 旗艦版 |C:\\Windows|\\Device\\Harddisk0\\Partition1";
NumberOfLicensedUsers = 0;
NumberOfProcesses = 115;
NumberOfUsers = 1;
OperatingSystemSKU = 1;
Organization = "Microsoft";
OSArchitecture = "64-bit";
OSLanguage = 2052;
OSProductSuite = 256;
OSType = 18;
Primary = TRUE;
ProductType = 1;
RegisteredUser = "PC";
SerialNumber = "00426-OEM-8992662-00006";
ServicePackMajorVersion = 1;
ServicePackMinorVersion = 0;
SizeStoredInPagingFiles = "6119656";
Status = "OK";
SuiteMask = 272;
SystemDevice = "\\Device\\HarddiskVolume1";
SystemDirectory = "C:\\Windows\\system32";
SystemDrive = "C:";
TotalVirtualMemorySize = "10217684";
TotalVisibleMemorySize = "4099868";
Version = "6.1.7601";
WindowsDirectory = "C:\\Windows";
};
import wmi
w = wmi.WMI()
obj = w.Win32_OperatingSystem()[0]
print("sn",obj.SerialNumber)
# sn 00426-OEM-8992662-00006
擷取實體磁盤資訊
wmi.Win32_DiskDrive()方法
import wmi
w = wmi.WMI()
disk = w.Win32_DiskDrive()[0]
print(disk)
instance of Win32_DiskDrive
{
BytesPerSector = 512;
Capabilities = {3, 4, 10};
CapabilityDescriptions = {"Random Access", "Supports Writing", "SMART Notification"};
Caption = "ST500LT0 12-1DG142 SCSI Disk Device";
ConfigManagerErrorCode = 0;
ConfigManagerUserConfig = FALSE;
CreationClassName = "Win32_DiskDrive";
Description = "磁盤驅動器";
DeviceID = "\\\\.\\PHYSICALDRIVE0";
FirmwareRevision = "0001";
Index = 0;
InterfaceType = "IDE";
Manufacturer = "(标準磁盤驅動器)";
MediaLoaded = TRUE;
MediaType = "Fixed hard disk media";
Model = "ST500LT0 12-1DG142 SCSI Disk Device";
Name = "\\\\.\\PHYSICALDRIVE0";
Partitions = 4;
PNPDeviceID = "SCSI\\DISK&VEN_ST500LT0&PROD_12-1DG142\\4&30B6A92E&0&010000";
SCSIBus = 1;
SCSILogicalUnit = 0;
SCSIPort = 0;
SCSITargetId = 0;
SectorsPerTrack = 63;
SerialNumber = " W3P2DXE1";
Signature = 2837888961;
Size = "500105249280";
Status = "OK";
SystemCreationClassName = "Win32_ComputerSystem";
SystemName = "QH-20181120YSCF";
TotalCylinders = "60801";
TotalHeads = 255;
TotalSectors = "976768065";
TotalTracks = "15504255";
TracksPerCylinder = 255;
};
擷取硬碟sn 、硬碟大小 、型号制造商 、硬碟型号
import wmi
w = wmi.WMI()
disk = w.Win32_DiskDrive()[0]
print("硬碟制造商Manufacturer",disk.Manufacturer)
print("硬碟型号", disk.Model)
print("硬碟sn", disk.SerialNumber)
print("硬碟大小", int(disk.Size) / (1024 * 1024 * 1024))
'''
硬碟制造商Manufacturer (标準磁盤驅動器)
硬碟型号 ST500LT0 12-1DG142 SCSI Disk Device
硬碟sn W3P2DXE1
硬碟大小 465.7593083381653
'''
Win32_NetworkAdapterConfiguration() 方法
函數功能: 用于網絡接口資訊對象,并存以清單形式
傳回參數: interfaceList
interfaceList: list 類型,list 中每個元素均為一個網絡接口資訊的 object
擷取所有網卡資訊
import wmi
w = wmi.WMI()
data = {}
count = 0
for nic in w.Win32_NetworkAdapterConfiguration():
if nic.MACAddress is not None:
count+=1
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'] = ""
data["nic%s" %count] = item_data
print(data)
'''
{
'nic1':
{
'macaddress': 'FE:F8:AE:B0:93:4D',
'model': '[00000012] Microsoft Virtual WiFi Miniport Adapter',
'name': 12, 'ipaddress': '', 'netmask': ''
},
'nic2':
{
'macaddress': 'E0:DB:55:EC:EF:DC',
'model': '[00000013] Realtek PCIe GBE Family Controller',
'name': 13,
'ipaddress': '',
'netmask': ''
},
'nic3':
{
'macaddress': 'FC:F8:AE:B0:93:51',
'model': '[00000016] Bluetooth 裝置(個人區域網)',
'name': 16,
'ipaddress': '',
'netmask': ''
},
'nic4':
{
'macaddress': '00:50:56:C0:00:01',
'model': '[00000018] VMware Virtual Ethernet Adapter for VMnet1',
'name': 18,
'ipaddress': '192.168.234.1',
'netmask': ('255.255.255.0', '64')
},
'nic5':
{
'macaddress': 'FC:F8:AE:B0:93:4D',
'model': '[00000019] Intel(R) Wireless-N 7260',
'name': 19,
'ipaddress': 'x.x.x.x',
'netmask': ('255.255.255.0', '64')
},
'nic6':
{
'macaddress': '00:50:56:C0:00:08',
'model': '[00000020] VMware Virtual Ethernet Adapter for VMnet8',
'name': 20,
'ipaddress': 'x.x.x.x',
'netmask': ('255.255.0.0', '64')
},
'nic7':
{
'macaddress': 'FE:F8:AE:B0:93:4E',
'model': '[00000023] Microsoft Virtual WiFi Miniport Adapter',
'name': 23,
'ipaddress': '',
'netmask': ''}
}
'''