0

I am running a python script as root, from this script I want to run on linux process as userA. There is many answers on how to do that but I also need to print the exit code recived from the process and that the real isuue here.

Is there a way of running a process as userA and also to print the return value ?

os.system("su userA -c 'echo $USER'")
answer = subprocess.call(["su userA -c './my/path/run.sh'"])
print(answer)
David
  • 169
  • 4
  • 16

2 Answers2

1

If you use os.fork (with an os.setuid inside the child) you can collect the status using os.waitpid.

pid = os.fork()
if pid == 0:
    os.setgid(...)
    os.setgroups(...)
    os.setuid(...)

    # do something and collect the exit status... for example
    #
    # using os.system:
    #
    #      return_value = os.system(.....) // 256
    #
    # or using subprocess:
    #
    #      p = subprocess.Popen(....)
    #      out, err = p.communicate()
    #      return_value = p.returncode
    #
    # Or you can simply exec (this will not return to python but the 
    # exit status will still be visible in the parent).  Note there are 
    # several os.exec* calls, so choose the one which you want.
    #
    #      os.exec...
    #
    
    os._exit(return_value)

pid, status = os.waitpid(pid, 0)
print(f"Child exit code was {status // 256}")

Here I recently posted an answer to a related question which was not so much focused on the return value but does include some more details of the values that you might pass to the os.setuid etc calls.

alani
  • 12,573
  • 2
  • 13
  • 23
1

When you're running a script and you want to print its return code, you must wait until its execution is done before executing the print command. The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. http://docs.python.org/library/subprocess.html

In your case:

    import subprocess
    process = subprocess.Popen('su userA -c ./my/path/run.sh', shell=True, stdout=subprocess.PIPE)
    process.wait()
    print process.returncode

Reference: https://stackoverflow.com/a/325474/13798864

bost
  • 38
  • 3