From 845559d045c44affadbf3f917cef486bb5345b61 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 | 9 +++++++++ unix-ffi/machine/manifest.py | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/unix-ffi/machine/machine/__init__.py b/unix-ffi/machine/machine/__init__.py index 80bf5da1a..9db98faa2 100644 --- a/unix-ffi/machine/machine/__init__.py +++ b/unix-ffi/machine/machine/__init__.py @@ -4,4 +4,13 @@ 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: + # unhexlify might not be available + return bytes([int(data[i : i + 2], 16) for i in range(0, 32, 2)]) + except OSError as e: + pass 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.