Python – How to find UUID of computer and set as variable

Question:

I have been looking all over the internet for a way to find a way to get UUID for a computer and set it as a variable in python.

Some of the ways I tried doing didn’t work.

Original idea:

import os
x = os.system("wmic diskdrive get serialnumber")
print(x)

However this does not work, and only returns 0.

I am wondering if their is a way i can find a unique Harddrive ID or any other type of identifier in python.

Asked By: Bill D

||

Answers:

The os.system function returns the exit code of the executed command, not the standard output of it.

According to Python official documentation:

On Unix, the return value is the exit status of the process encoded in the format specified for wait().

On Windows, the return value is that returned by the system shell
after running command.

To get the output as you want, the recommended approach is to use some of the functions defined in the subprocess module. Your scenario is pretty simple, so subprocess.check_output works just fine for it.

You just need to replace the code you posted code with this instead:

import subprocess
x = subprocess.check_output('wmic csproduct get UUID')
print(x)
Answered By: slashCoder

If the aim is to get the serial number of the HDD, then one can do:

In Linux (replace /dev/sda with the block disk identifier for which you want the info):

>>> import os
>>> os.popen("hdparm -I /dev/sda | grep 'Serial Number'").read().split()[-1]

In Windows:

>>> import os
>>> os.popen("wmic diskdrive get serialnumber").read().split()[-1]
Answered By: Nehal J Wani

For Linux try this:

def get_uuid():
    dmidecode = subprocess.Popen(['dmidecode'],
                                      stdout=subprocess.PIPE,
                                      bufsize=1,
                                      universal_newlines=True
                                      )

    while True:
        line = dmidecode.stdout.readline()
        if "UUID:" in str(line):
            uuid = str(line).split("UUID:", 1)[1].split()[0]
            return uuid
        if not line:
            break

my_uuid = get_uuid()
    print("My ID:", my_uuid)
Answered By: Vladimír

For windows:

import wmi
import os

def get_serial_number_of_system_physical_disk():
    c = wmi.WMI()
    logical_disk = c.Win32_LogicalDisk(Caption=os.getenv("SystemDrive"))[0]
    partition = logical_disk.associators()[1]
    physical_disc = partition.associators()[0]
    return physical_disc.SerialNumber
Answered By: Ahmet Yıldırım

for windows i do work with this one and it works perfectly:

import subprocess

UUID = str(subprocess.check_output('wmic csproduct get UUID'),'utf-8').split('n')[1].strip()

print(UUID)
Answered By: Nyx Fallaga TN
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.