CarloMatto
CarloMatto

Reputation: 183

Get machine-id in linux with python

I'm looking for getting my linux server's machine-id in a python script.

I try with:

import subprocess 
machine_id = subprocess.check_output('cat /var/lib/dbus/machine-id')

or

import subprocess 
machine_id = subprocess.check_output('cat /etc/machine-id')

but in both the situation a get this error:

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "/usr/lib/python3.8/subprocess.py", line 415, in check_output
     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
   File "/usr/lib/python3.8/subprocess.py", line 493, in run
     with Popen(*popenargs, **kwargs) as process:
   File "/usr/lib/python3.8/subprocess.py", line 858, in __init__
     self._execute_child(args, executable, preexec_fn, close_fds,   
   File "/usr/lib/python3.8/subprocess.py", line 1704, in _execute_child
     raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'cat
 /etc/machine-id'

What can I do ?

Upvotes: 2

Views: 814

Answers (1)

Amin
Amin

Reputation: 2853

You should either pass your command as a list or set shell=True:

machine_id = subprocess.check_output(['cat', '/var/lib/dbus/machine-id'])

or

machine_id = subprocess.check_output('cat /var/lib/dbus/machine-id', shell=True)

You can find useful docs in subprocess_docs, as it says:

args should be a sequence of program arguments or else a single string or path-like object. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence.

The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence. On POSIX with shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. That is to say, Popen does the equivalent of: Popen(['/bin/sh', '-c', args[0], args1, ...])

Upvotes: 1

Related Questions