Python - 如何找到计算机的 UUID 并设置为变量

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

我一直在整个互联网上寻找一种方法来找到一种方法来获取计算机的 UUID 并将其设置为 python 中的变量。

我试过的一些方法没有用。

最初的想法:

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

不过这样不行,只有returns0。

我想知道他们是否是我可以在 python 中找到唯一硬盘驱动器 ID 或任何其他类型标识符的方法。

os.system函数returns执行命令的退出代码,不是它的标准输出。

根据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.

要获得所需的输出,推荐的方法是使用子流程模块中定义的一些函数。您的方案非常简单,因此 subprocess.check_output 可以正常工作。

您只需要将您发布的代码替换为:

import subprocess
x = subprocess.check_output('wmic csproduct get UUID')
print(x)

如果目的是获取硬盘的序列号,那么可以这样做:

在 Linux 中(将 /dev/sda 替换为您想要其信息的块磁盘标识符):

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

在Windows中:

>>> import os
>>> os.popen("wmic diskdrive get serialnumber").read().split()[-1]

对于 Linux 试试这个:

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)

对于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