From 12410fde93eab2fd615a929cdad0d8654c479e81 Mon Sep 17 00:00:00 2001 From: Alessandro Gatti Date: Sun, 15 Mar 2026 10:21:32 +0100 Subject: [PATCH] machine: Retrieve an unique identifier if one is known. This commit adds a proper implementation for "machine.unique_id" for selected systems, as opposed to returning a fixed value in every case. On a Unix system there are several incompatible ways to retrieve something that can be called an unique machine identifier. However, the only semblance of a specification comes from freedesktop.org, which says that a file called "/etc/machine-id" has to exist and must contain a 32-digits long hexadecimal identifier. Given that the current specification is the DBus unique identifier retrieval mechanism made official, if the identifier file is not found the code will attempt to read the file provided by DBus. These changes only apply to Linux and recent BSD systems. On other systems the old, fixed value for the machine identifier will be returned instead - to avoid breaking compatibility with existing code. The specification used in this commit is available at https://www.freedesktop.org/software/systemd/man/latest/machine-id.html. Signed-off-by: Alessandro Gatti --- unix-ffi/machine/machine/__init__.py | 13 +++++++++++++ unix-ffi/machine/manifest.py | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/unix-ffi/machine/machine/__init__.py b/unix-ffi/machine/machine/__init__.py index 80bf5da1a..72a5d9403 100644 --- a/unix-ffi/machine/machine/__init__.py +++ b/unix-ffi/machine/machine/__init__.py @@ -4,4 +4,17 @@ def unique_id(): + for base in ("/etc", "/var/lib/dbus"): + try: + with open(base + "/machine-id", "rb") as source: + data = source.read(32) + if len(data) == 32: + for byte in data: + if byte not in b"0123456789abcdef": + break + # unhexlify might not be available + return bytes([int(data[i : i + 2], 16) for i in range(0, len(data), 2)]) + except OSError as e: + if "ENOENT" not in str(e): + raise return b"upy-non-unique" diff --git a/unix-ffi/machine/manifest.py b/unix-ffi/machine/manifest.py index f7c11b81a..bdfb6a95f 100644 --- a/unix-ffi/machine/manifest.py +++ b/unix-ffi/machine/manifest.py @@ -1,4 +1,4 @@ -metadata(version="0.2.2") +metadata(version="0.2.3") # Originally written by Paul Sokolovsky.