Calling of GetVolumeInformation returns empty serial number

eryk sun eryksun at gmail.com
Tue Nov 7 07:10:37 EST 2017


On Tue, Nov 7, 2017 at 7:58 AM, Durumdara <durumdara at gmail.com> wrote:
>
> I want to get the serial number of the drives (without external modules
> like Win32 or WMI).

The volume serial number is more easily available as
os.stat(drive).st_dev, which comes from calling
GetFileInformationByHandle. Note that despite using the volume serial
number (VSN) as the nearest equivalent of POSIX st_dev, there is no
requirement that the VSN is unique or even non-zero. The same applies
to the file index number that's used for POSIX st_ino. For example,
both values are 0 on a WebDav drive, for which Python's implementation
of os.path.samefile is useless. Practically speaking, however, it's
good enough in most cases, especially for mounted disk volumes.

That said, maybe what you really want is the hardware (disk) serial
number -- not a volume serial number. The easiest way to get that is
via WMI. You can use subprocess to run wmic.exe if you don't want an
external dependency. You can also get the disk serial number by
calling DeviceIoControl via ctypes. This is a fairly complex
IOCTL_STORAGE_QUERY_PROPERTY request, with an input
STORAGE_PROPERTY_QUERY structure requesting the StorageDeviceProperty.
The result is a STORAGE_DEVICE_DESCRIPTOR structure that has a
SerialNumberOffset field that's the byte offset from the beginning of
the buffer of the serial number as a null-terminated string.

Getting back to the VSN, note that the mount-point manager doesn't
rely on it as a unique identifier. For associating volume devices with
logical DOS drives and volume GUID names (i.e. names like
"Volume{12345678-0000-0000-0000-123456789abc}", which are used to
mount volumes as NTFS junctions), the mount-point manager queries a
unique ID via IOCTL_MOUNTDEV_QUERY_UNIQUE_ID. Sometimes the volume
driver returns a unique ID that's very long -- over 200 bytes. This
doesn't matter because it's only used to uniquely associate a GUID
name (and maybe a DOS drive) with the given volume when the system
boots. This association is persisted in HKLM\System\MountedDevices.



More information about the Python-list mailing list