I have this simple python script that run as root, but will execute subprocesses as some other user:
#!/usr/bin/env python2
import subprocess
import os
def demote(user_uid):
def result():
os.setuid(user_uid)
return result
cmd = "echo $USER"
proc = subprocess.Popen(cmd, preexec_fn=demote(1000), stdout=subprocess.PIPE, shell=True)
output = proc.communicate()[0]
print output
If cmd is "sleep 60" then the script spawns sleep as the user:
# ps -ef | grep sleep
dave 17812 17811 0 17:05 pts/5 00:00:00 /usr/bin/sleep 60
However, if cmd is 'echo $USER', the outout is "root". Is there someone I need to do to get the user's env if I spawn the subprocess as a nother user?