Python3使用wmi获取系统信息-以获取硬盘分区为例

在python中使用wmi和在c++中使用并没有太多区别,如果考虑兼容性的话个人还是推荐使用win api方式获取信息,因为xp中默认是不开启wmi的,并且用户或软件可以关闭系统的wmi功能,会出现获取不到数据的情况。

安装所需依赖

pip3 install wmi
pip3 install pywin32

代码round(int(), 2)是保留两位小数的功能,

py库包含import os, sys, wmi

硬盘信息获取代码

def get_disk_info():
    tmplist = []
    c = wmi.WMI()
    for physical_disk in c.Win32_DiskDrive():
        tmpdict = {}
        tmpdict["Caption"] = physical_disk.Caption
        tmpdict["Size"] = round(int(physical_disk.Size) / (1024 * 1024 * 1024), 2)
        tmpdict["DeviceID"] = physical_disk.DeviceID
        tmpdict["SerialNumber"] = physical_disk.SerialNumber
        tmplist.append(tmpdict)
    return tmplist
physical_disk包含的字段如下,根据自己需要获取字段
{
	BytesPerSector = 512;
	Capabilities = {3, 4};
	CapabilityDescriptions = {"Random Access", "Supports Writing"};
	Caption = "TOSHIBA MQ01ABD050";
	ConfigManagerErrorCode = 0;
	ConfigManagerUserConfig = FALSE;
	CreationClassName = "Win32_DiskDrive";
	Description = "磁盘驱动器";
	DeviceID = "\\\\.\\PHYSICALDRIVE0";
	FirmwareRevision = "AX002J";
	Index = 0;
	InterfaceType = "IDE";
	Manufacturer = "(标准磁盘驱动器)";
	MediaLoaded = TRUE;
	MediaType = "Fixed hard disk media";
	Model = "TOSHIBA MQ01ABD050";
	Name = "\\\\.\\PHYSICALDRIVE0";
	Partitions = 3;
	PNPDeviceID = "SCSI\\DISK&VEN_TOSHIBA&PROD_MQ01ABD050\\4&3BBA67D&0&000000";
	SCSIBus = 0;
	SCSILogicalUnit = 0;
	SCSIPort = 0;
	SCSITargetId = 0;
	SectorsPerTrack = 63;
	SerialNumber = "XXXXXXXXXXXXX";//硬盘序列号
	Size = "500105249280";
	Status = "OK";
	SystemCreationClassName = "Win32_ComputerSystem";
	SystemName = "DESKTOP-BG7EQ0M";
	TotalCylinders = "60801";
	TotalHeads = 255;
	TotalSectors = "976768065";
	TotalTracks = "15504255";
	TracksPerCylinder = 255;
};

磁盘获取是从硬盘到盘符的获取,并非直接枚举盘符

for physical_disk in c.Win32_DiskDrive() #获取全部硬盘
for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition")#获取单个硬盘内的所有盘符
for logical_disk in partition.associators("Win32_LogicalDiskToPartition")#获取单个盘符的信息

代码,有需要可将physical_disk的属性记录到磁盘信息里面

def get_fs_info():
    tmplist = []
    c = wmi.WMI()
    for physical_disk in c.Win32_DiskDrive():
        for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"):
            for logical_disk in partition.associators("Win32_LogicalDiskToPartition"):
                tmpdict = {}
                tmpdict["Caption"] = logical_disk.Caption
                tmpdict["DiskTotal"] = round(int(logical_disk.Size) / (1024 * 1024 * 1024), 2)
                tmpdict["DeviceID"] = logical_disk.DeviceID
                tmpdict["FileSystem"] = logical_disk.FileSystem
                tmplist.append(tmpdict)
    return tmplist

运行结果

你可能感兴趣的:(编程,wmi,python3,硬盘信息)