Run child processes as different user from a long running Python process

Viewed 60979

I've got a long running, daemonized Python process that uses subprocess to spawn new child processes when certain events occur. The long running process is started by a user with super user privileges. I need the child processes it spawns to run as a different user (e.g., "nobody") while retaining the super user privileges for the parent process.

I'm currently using

su -m nobody -c <program to execute as a child>

but this seems heavyweight and doesn't die very cleanly.

Is there a way to accomplish this programmatically instead of using su? I'm looking at the os.set*uid methods, but the doc in the Python std lib is quite sparse in that area.

5 Answers

The new versions of Python (3.9 onwards) support user and group option out of the box:

process = subprocess.Popen(args, user=username)

The new versions also provide a subprocess.run function. It is a simple wrapper around subprocess.Popen. While suprocess.Popen runs the commands in the background, subprocess.run runs the commands and wait for their completion.

Thus we can also do:

subprocess.run(args, user=username)
Related