Python Disable and Enable Root Privileges

2019-07-15 08:31发布

问题:

I have segment of code that I'd like run as non-root. If the program is run as non-root, nothing needs to happen. But if the program is run as root, then root privileges need to be dropped, the segment of code executed, then root privileges enabled again. How do you write code for the enable/disable?

回答1:

Try the following:

import os
print "user who executed the code: %d" % os.getuid()
print "current effective user: %d" % os.geteuid()
if os.getuid() == 0:
    os.seteuid(65534) # user id of the user "nobody"
    print "current effective user: %d" % os.geteuid()
    # do what you need to do with non-root privileges here, e.g. write to a file
    print >> open("/tmp/foobar.txt", "w"), "hello world"
    os.seteuid(0)
print "current effective user: %d" % os.geteuid()

Running this as root outputs:

user who executed the code: 0
current effective user: 0
current effective user: 65534
current effective user: 0


回答2:

Try os.getuid() and os.setuid(). You can use them to switch user within your script.



标签: python root