0

i want to start a linux command with python but without printing the output, i olso want to save the output. i tried this:

user = os.system('whoami')
if user == 'root':
    print('')
elif:
    print('please run as root')
    exit()

but then its printing 'please run as root' even if i run it as root. i olso tried this(just to check what user is):

user = os.system('whoami')
print(str(user))

but its printing '0'

my goal is to check what user is running the program, but without printing the user. (i use arch)

rdex999
  • 3
  • 4
  • 2
    Perhaps have a look at the [`subprocess.run`](https://docs.python.org/3/library/subprocess.html#subprocess.run) instead for executing commands, but really to get the UID rather [`os.geteuid`](https://docs.python.org/3/library/os.html#os.getuid) (if you care the user is root) or [`os.getuid`](https://docs.python.org/3/library/os.html#os.geteuid) (if you care the process can do root stuff) for what you are actually after in this case. – Ondrej K. Jun 24 '22 at 09:41
  • 3
    `os.system()` return the *exit code* of the call, not the output. – Klaus D. Jun 24 '22 at 09:43
  • 2
    use `os.getlogin()` to get the current username – B1TC0R3 Jun 24 '22 at 09:44
  • 1
    Does this answer your question? [Running shell command and capturing the output](https://stackoverflow.com/questions/4760215/running-shell-command-and-capturing-the-output) – Mime Jun 24 '22 at 09:50

1 Answers1

1

perhaps you should have a look on subprocess.run, there is a parameter in the function called capture output, in the docs is described as follows:

If capture_output is true, stdout and stderr will be captured. When used, the internal Popen object is automatically created with stdout=PIPE and stderr=PIPE. The stdout and stderr arguments may not be supplied at the same time as capture_output. If you wish to capture and combine both streams into one, use stdout=PIPE and stderr=STDOUT instead of capture_output.

in the docs there is an example that shows how to get output from commands:

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n',stderr=b'')

if you just want to get the current user, i would suggest os.getlogin:

>>> import os
>>> if os.getlogin() != 'root':
...     print("please run as root!")
please run as root!

NOTE: I would also suggest to not use shell=True in the arguments, provides lots of security issues.

XxJames07-
  • 1,833
  • 1
  • 4
  • 17