Windows Management Instrumentation (WMI) 提供了統一介面查詢系統硬體與作業系統資訊。Python 透過 wmi 套件即可輕鬆存取。本文整理一支完整腳本,可一次擷取作業系統版本、記憶體、硬碟、CPU 及網路介面卡資訊。
pip install wmi pywin32
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wmi
import sys, time, platform
def get_system_info(os_type):
"""取得作業系統版本"""
print("\nOperating system:")
if os_type == "Windows":
c = wmi.WMI()
for sys_obj in c.Win32_OperatingSystem():
print(f"\tVersion :\t{sys_obj.Caption}")
print(f"\tBuild :\t{sys_obj.BuildNumber}")
def get_memory_info(os_type):
"""取得實體與虛擬記憶體"""
print("\nmemory_info:")
if os_type == "Windows":
c = wmi.WMI()
cs = c.Win32_ComputerSystem()[0]
pfu = c.Win32_PageFileUsage()[0]
mem_total = int(cs.TotalPhysicalMemory) / 1024 / 1024
swap_total = int(pfu.AllocatedBaseSize)
print(f"\tTotalPhysicalMemory :\t{mem_total:.0f} MB")
print(f"\tSwapTotal :\t{swap_total} MB")
def get_disk_info(os_type):
"""取得實體磁碟資訊"""
print("\ndisk_info:")
if os_type == "Windows":
c = wmi.WMI()
for disk in c.Win32_DiskDrive():
if disk.Size:
size_gb = int(disk.Size) / 1024 / 1024 / 1024
print(f"\t{disk.Caption} :\t{size_gb:.1f} GB")
def get_cpu_info(os_type):
"""取得 CPU 型號、核心數、時脈"""
print("\ncpu_info:")
if os_type == "Windows":
c = wmi.WMI()
for cpu in c.Win32_Processor():
cores = getattr(cpu, 'NumberOfCores', 1)
print(f"\tCpuType :\t{cpu.Name.strip()}")
print(f"\tCpuCores :\t{cores}")
print(f"\tCpuClock :\t{cpu.MaxClockSpeed} MHz")
def get_network_info(os_type):
"""取得啟用 IP 的網卡與 TCP 連線數"""
print("\nnetwork_info:")
if os_type == "Windows":
c = wmi.WMI()
for nic in c.Win32_NetworkAdapterConfiguration(IPEnabled=True):
print(f"\t{nic.Description}")
print(f"\t\tMAC :\t{nic.MACAddress}")
print(f"\t\tIP :\t{nic.IPAddress[0]}")
print(f"\t\tSubnet :\t{nic.IPSubnet[0]}")
for tcp in c.Win32_PerfRawData_Tcpip_TCPv4():
print(f"\tTCP Connections :\t{tcp.ConnectionsEstablished}")
if __name__ == "__main__":
os_name = platform.system()
get_system_info(os_name)
get_memory_info(os_name)
get_disk_info(os_name)
get_cpu_info(os_name)
get_network_info(os_name)
Operating system:
Version : Microsoft Windows 10 Pro
Build : 19045
memory_info:
TotalPhysicalMemory : 16384 MB
SwapTotal : 8192 MB
disk_info:
Samsung SSD 970 EVO 500GB : 465.8 GB
cpu_info:
CpuType : Intel(R) Core(TM) i7-9700K CPU @ 3.60GHz
CpuCores : 8
CpuClock : 3600 MHz
network_info:
Intel(R) Ethernet Connection (2) I219-V
MAC : 00:11:22:33:44:55
IP : 192.168.1.100
Subnet : 255.255.255.0
TCP Connections : 42
.encode('GBK'),Python 3 直接列印 Unicode 即可。