Reputation: 69
I want to run a python program using sudo (e.g. sudo python test.py
) but within the python program when I use os.system(<some command>)
to invoke other processes, I want to run them as a non-root user.
Is this doable?
Thanks!
Upvotes: 0
Views: 1195
Reputation: 69
Another way to do this is to add a prefix sudo -u username
in front of the command one wants to run to execute as that specific user. For example, one can use os.system('sudo -u user_a python test.py')
to run test.py
inside a python script as user_a
.
Upvotes: 0
Reputation: 13079
Example:
import os
import pwd
username = "nobody"
pwent = pwd.getpwnam(username)
uid = pwent.pw_uid
gid = pwent.pw_gid
pid = os.fork()
if pid == 0:
# child
# relinquish any privileged groups before we call setuid
# (not bothering to load the target user's supplementary groups here)
os.setgid(gid)
os.setgroups([])
# now relinquish root privs
os.setuid(uid)
# os.setuid should probably raise an exception if it fails,
# but I'm paranoid so...
if os.getuid() != uid:
print("setuid failed - bailing")
os._exit(1)
return_value = os.system("id") // 256 # or whatever
os._exit(return_value)
# parent
os.waitpid(pid, 0)
print("parent continues (still root here)")
os.system("id")
Gives:
uid=65534(nobody) gid=65534(nogroup) groups=65534(nogroup)
parent continues (still root here)
uid=0(root) gid=0(root) groups=0(root)
Upvotes: 1