萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 跨平台獲取硬件信息:Windows WMI / Linux /proc / macOS system_profiler

跨平台策略概覽

平台核心接口關鍵工具/庫典型數據源
WindowsWMI (Windows Management Instrumentation)wmi, pywin32Win32_Processor, Win32_BaseBoard, Win32_DiskDrive
Linux虛擬文件系統 /proc, /sys標準庫 open/read/proc/cpuinfo, /proc/meminfo, /sys/class/dmi/id/
macOSsystem_profiler 命令行工具subprocess + plist 解析SPHardwareDataType, SPSerialATADataType

Windows: WMI 查詢


# pip install wmi pywin32
import wmi

def get_windows_hardware():
    c = wmi.WMI()
    info = {}
    
    # CPU
    cpus = c.Win32_Processor()
    info['cpu'] = [{
        'name': cpu.Name.strip(),
        'cores': cpu.NumberOfCores,
        'threads': cpu.NumberOfLogicalProcessors,
        'max_clock': cpu.MaxClockSpeed,
        'processor_id': cpu.ProcessorId.strip()
    } for cpu in cpus]
    
    # 主板
    boards = c.Win32_BaseBoard()
    info['motherboard'] = [{
        'manufacturer': b.Manufacturer.strip(),
        'product': b.Product.strip(),
        'serial': b.SerialNumber.strip()
    } for b in boards]
    
    # 內存
    memory = c.Win32_PhysicalMemory()
    info['memory'] = [{
        'capacity_gb': round(int(m.Capacity) / 1024**3, 2),
        'speed_mhz': m.Speed,
        'manufacturer': m.Manufacturer.strip(),
        'part_number': m.PartNumber.strip()
    } for m in memory]
    
    # 磁盤
    disks = c.Win32_DiskDrive()
    info['disks'] = [{
        'model': d.Model.strip(),
        'size_gb': round(int(d.Size) / 1024**3, 2),
        'interface': d.InterfaceType,
        'serial': d.SerialNumber.strip()
    } for d in disks]
    
    return info

Linux: 解析 /proc 文件系統


import re

def get_linux_hardware():
    info = {}
    
    # CPU 信息
    with open('/proc/cpuinfo') as f:
        cpuinfo = f.read()
    
    cpus = []
    current = {}
    for line in cpuinfo.split('\n'):
        if not line.strip():
            if current:
                cpus.append(current)
                current = {}
        else:
            key, _, val = line.partition(':')
            current[key.strip()] = val.strip()
    if current: cpus.append(current)
    
    # 去重邏輯核心
    physical_ids = set(c.get('physical id') for c in cpus)
    info['cpu'] = {
        'model': cpus[0].get('model name', '').strip(),
        'physical_cores': len(physical_ids),
        'logical_cores': len(cpus),
        'cache_kb': cpus[0].get('cache size', ''),
        'flags': cpus[0].get('flags', '').split()
    }
    
    # 內存信息
    meminfo = {}
    with open('/proc/meminfo') as f:
        for line in f:
            key, _, val = line.partition(':')
            meminfo[key.strip()] = val.strip()
    info['memory'] = {
        'total_kb': int(meminfo.get('MemTotal', '0').split()[0]),
        'available_kb': int(meminfo.get('MemAvailable', '0').split()[0])
    }
    
    # DMI 信息 (需 root 讀取 /sys/class/dmi/id/)
    dmi_path = '/sys/class/dmi/id'
    info['system'] = {}
    for attr in ['product_name', 'product_version', 'board_vendor', 'board_name', 'chassis_vendor']:
        path = f"{dmi_path}/{attr}"
        try:
            with open(path) as f:
                info['system'][attr] = f.read().strip()
        except:
            info['system'][attr] = 'N/A (need root)'
    
    return info

macOS: system_profiler + plist


import subprocess
import plistlib

def get_macos_hardware():
    # 獲取硬件信息為 XML (plist) 格式
    result = subprocess.run([
        '/usr/sbin/system_profiler', 
        'SPHardwareDataType', 
        '-xml'
    ], capture_output=True, text=False)
    
    data = plistlib.loads(result.stdout)
    hw = data[0]['_items'][0] if data else {}
    
    return {
        'model': hw.get('machine_model', ''),
        'cpu': {
            'name': hw.get('cpu_type', ''),
            'cores': hw.get('number_processors', 0),
            'logical_cores': hw.get('number_processors', 0),  # 簡化
            'clock_mhz': hw.get('current_processor_speed', 0)
        },
        'memory': {
            'total_gb': round(hw.get('physical_memory', 0) / 1024**3, 2)
        },
        'serial': hw.get('serial_number', ''),
        'uuid': hw.get('platform_UUID', '')
    }

統一跨平台接口


import platform
import json

def get_hardware_info():
    system = platform.system().lower()
    
    if system == 'windows':
        return get_windows_hardware()
    elif system == 'linux':
        return get_linux_hardware()
    elif system == 'darwin':
        return get_macos_hardware()
    else:
        raise NotImplementedError(f"Unsupported platform: {system}")

if __name__ == '__main__':
    info = get_hardware_info()
    print(json.dumps(info, indent=2, ensure_ascii=False))

第三方統一庫推薦

  • psutil:pip install psutil,跨平台獲取 CPU/內存/磁盤/網絡/進程信息,首選
  • cpuinfo:pip install py-cpuinfo,專注 CPU 詳細信息
  • dmidecode (Linux):sudo dmidecode 獲取完整 DMI/SMBIOS 信息

psutil 快速上手


import psutil

print(f"CPU: {psutil.cpu_count(logical=False)}C/{psutil.cpu_count()}T @ {psutil.cpu_freq().current:.0f}MHz")
print(f"Memory: {psutil.virtual_memory().total / 1024**3:.1f} GB")
print(f"Disks: {[(p.device, p.mountpoint, p.fstype) for p in psutil.disk_partitions()]}")
print(f"Network: {list(psutil.net_if_addrs().keys())}")

根據場景選擇:psutil 覆蓋 90% 需求;特殊硬件序列號、主板信息需平台原生方案;自動化資產掃描建議結合 Ansible/SaltStack 等運維工具。

copyright © 萬盛學電腦網 all rights reserved