Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute 'ls' command as a different User within python script

Folks, Here's what I am trying to do: my script will be running as root, I wish to execute various commands (say ls, rm, touch etc) as different users.

The problem I have is that using preexec_fn=os.setuid(userid)) is setting the userid of the parent process as well. Suggestions please? Is preexec_fn the wrong way to achieve this? A further note is that this needs to be in the twisted way (which I might not be). Is getProcessOutputAndValue the way to go? If so, how to do something like this?

print 'uid is %s' % os.getuid()
cmdstr = ['ls']
process = subprocess.Popen(cmdstr,stdout=subprocess.PIPE, stderr=subprocess.STDOUT, preexec_fn=os.setuid(10033))
print 'uid of parent after child startup is %s' % os.getuid()
process.wait()
print 'uid of parent after child finished is %s' % os.getuid()

output:

uid is 0
uid of parent after child startup is 10033
uid of parent after child finished is 10033
like image 889
helpmelearn Avatar asked Nov 21 '25 22:11

helpmelearn


1 Answers

Your problem is that you are accidentally calling the preexec_fn when you're only trying to pass a callback to Popen.

Try this instead:

def my_preexec_fn():
    os.setuid(10033)
process = subprocess.Popen(cmdstr,stdout=subprocess.PIPE, stderr=subprocess.STDOUT, preexec_fn=my_preexec_fn)
like image 89
rlibby Avatar answered Nov 23 '25 13:11

rlibby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!