Get the serial number of the hard disk who host windows os

464 Views Asked by At

I'm trying to get the serial number of the hard disk who host windows os in a consistant way through python calling windows cmd from subprocess

So far using :

wmic diskdrive get serialnumber,index

Which give me back something like :

Index  SerialNumber
1      000000001536
0      0025_XXXX_2142_XXXX.
2      000000001536

However the first, nor the index 0 is not always the hardrive with the OS... (as mentionned in the answer in Get hard disk serial number from local disk in batch)

Is there a command to get the hard drive serial number of where is installer the Windows OS ?

Thanks,

2

There are 2 best solutions below

0
Nuopel On BEST ANSWER

Thanks to your suggestions :

For windows > 7, In a powershell with the SystemDrive environnement variable, the serial number of the current used os can be found with :

get-partition -DriveLetter ($Env:SystemDrive).Replace(':','') | get-disk | % {$_.SerialNumber}

For older versions of windows,in cmd.exe, wmic can be used with :

wmic /namespace:\\root\microsoft\windows\storage path msft_disk WHERE "IsSystem='TRUE'" get serialnumber

In python :

import subprocess

def get_serial():
    try:
        cmd = r'wmic /namespace:\\root\microsoft\windows\storage path msft_disk WHERE "IsSystem=\'TRUE\'" get serialnumber'.replace(
            "\\'", "'")
        serial = subprocess.check_output(cmd)


    except:
        cmd = "get-partition -DriveLetter ($Env:SystemDrive).Replace(':','') | get-disk | % {$_.SerialNumber}"
        ouput = subprocess.run(["powershell", "-Command", cmd], capture_output=True)
        serial = ouput.stdout

    return serial

Note that calling a powershell and get-partition is fairly slow...

3
Compo On

If you need just the serial number, you could try the following WMIC.exe command, on supported systems:

WMIC.exe /NameSpace:\\ROOT\Microsoft\Windows\Storage Path MSFT_Disk Where IsSystem=TRUE Get SerialNumber

Running the WMIC.exe command as an argument to cmd.exe, on supported systems, and output the same information you have indicated, (but only the OS drive), and returning just th serial number, would look like this:

cmd.exe /D /Q /C "For /F "Tokens=1,* Delims==" %G In ('%SystemRoot%\System32\wbem\WMIC.exe LogicalDisk Where DeviceID^='%SystemDrive%' Assoc:'List' /AssocClass:'Win32_LogicalDiskToPartition' 2^>NUL') Do If "%G" == "DiskIndex" %SystemRoot%\System32\wbem\WMIC.exe DiskDrive Where Index=%H Get SerialNumber"

Obviously if you are running either of these, presumably via the subprocess module, you would need to do so in a way that correctly handles all of the shown backward slashes, quotes, commas etc.

I would also always strongly advise that you use fully qualified absolute paths. WMIC.exe should always be located on the System drive, under \Windows\System32\wbem\, and cmd.exe also on the System drive, under \Windows\System32\.