Skip to content

Commit 75eb4aa

Browse files
agattidpgeorge
authored andcommitted
unix-ffi/machine: Retrieve a 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 <a.gatti@frob.it>
1 parent 47fec41 commit 75eb4aa

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

unix-ffi/machine/machine/__init__.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,13 @@
44

55

66
def unique_id():
7+
for base in ("/etc", "/var/lib/dbus"):
8+
try:
9+
with open(base + "/machine-id", "rb") as source:
10+
data = source.read(32)
11+
if len(data) == 32:
12+
# unhexlify might not be available
13+
return bytes([int(data[i : i + 2], 16) for i in range(0, 32, 2)])
14+
except OSError as e:
15+
pass
716
return b"upy-non-unique"

unix-ffi/machine/manifest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
metadata(version="0.2.2")
1+
metadata(version="0.2.3")
22

33
# Originally written by Paul Sokolovsky.
44

0 commit comments

Comments
 (0)