running a process as a different user from Python

EEP picture EEP · Dec 11, 2012 · Viewed 32.6k times · Source

I am running a script as userA with root access, from this script I want to make a popen() call and run a different process as userB.

os.setuid() does not seem to work for this (unless I am doing this wrong?), and I would like to avoid a linux based solution such as su -userB -c <command>

Is there a pythonic way of running a process as userB while the script is running as userA?

Answer

Andrew Clark picture Andrew Clark · Dec 11, 2012

The following answer has a really nice approach for this: https://stackoverflow.com/a/6037494/505154

There is a working code example there, but the summary is to use subprocess.Popen() with a preexec_fn to set up the environment of the subprocess so that it executes as another user.