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.