如何通过Python调用CMD获取Windows系统所在硬盘的序列号?
获取Windows系统所在硬盘物理序列号的稳定方法
你当前使用wmic diskdrive get serialnumber,index命令无法稳定定位系统盘,因为磁盘的Index序号不固定,无法通过Index直接关联系统所在的物理硬盘。以下是两种可靠的解决方案:
一、PowerShell精准查询(推荐)
PowerShell的CIM关联查询可以从系统盘符直接追溯到对应的物理硬盘,完全不受磁盘Index顺序影响,是最稳定的方式:
直接执行的PowerShell命令
Get-CimInstance Win32_OperatingSystem | Select-Object -ExpandProperty SystemDrive | ForEach-Object { Get-CimAssociatedInstance -InputObject (Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='$_'") -ResultClassName Win32_DiskPartition | Get-CimAssociatedInstance -ResultClassName Win32_DiskDrive | Select-Object Index, SerialNumber }
Python调用示例
通过subprocess模块调用上述PowerShell命令,处理输出结果:
import subprocess def get_system_disk_serial(): # 构造PowerShell命令 ps_cmd = ''' Get-CimInstance Win32_OperatingSystem | Select-Object -ExpandProperty SystemDrive | ForEach-Object { Get-CimAssociatedInstance -InputObject (Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='$_'") -ResultClassName Win32_DiskPartition | Get-CimAssociatedInstance -ResultClassName Win32_DiskDrive | Select-Object -ExpandProperty SerialNumber } ''' # 执行命令并捕获输出 result = subprocess.run( ["powershell", "-Command", ps_cmd], capture_output=True, text=True, check=False ) if result.returncode == 0: # 清理输出空白字符 serial = result.stdout.strip() return serial if serial else None return None # 调用并打印结果 system_disk_serial = get_system_disk_serial() if system_disk_serial: print(f"系统所在硬盘物理序列号: {system_disk_serial}") else: print("无法获取系统硬盘序列号")
二、WMIC链式关联查询(备选)
如果必须使用WMIC命令,可以通过「逻辑盘→磁盘分区→磁盘驱动器」的关联关系查询:
- 先获取系统盘对应的磁盘分区ID:
wmic path win32_logicaldisk where "DeviceID='C:'" get DeviceID /format:list wmic path win32_logicaldisktodiskpartition where "Antecedent like '%C:%'" get Dependent /format:list - 根据分区ID获取对应的磁盘驱动器序列号:
wmic path win32_diskdrive where "DeviceID='<分区对应的磁盘ID>'" get SerialNumber /format:list
这种方式需要手动解析关联关系,步骤繁琐,不如PowerShell方案简洁可靠。
注意:区分物理硬盘序列号和卷序列号:
wmic logicaldisk get VolumeSerialNumber获取的是逻辑盘的卷序列号,并非物理硬盘的硬件序列号,不要混淆。
内容的提问来源于stack exchange,提问作者Nuopel
相关产品推荐
相关产品推荐

