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)

4
  • 2
    Perhaps have a look at the subprocess.run instead for executing commands, but really to get the UID rather os.geteuid (if you care the user is root) or os.getuid (if you care the process can do root stuff) for what you are actually after in this case. Commented Jun 24, 2022 at 9:41
  • 3
    os.system() return the exit code of the call, not the output. Commented Jun 24, 2022 at 9:43
  • 2
    use os.getlogin() to get the current username Commented Jun 24, 2022 at 9:44
  • 1
    Does this answer your question? Running shell command and capturing the output Commented Jun 24, 2022 at 9:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.