Python Disable and Enable Root Privileges

2019-07-15 08:08发布

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?

标签: python root
2条回答
该账号已被封号
2楼-- · 2019-07-15 08:49

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
查看更多
Melony?
3楼-- · 2019-07-15 08:53

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

查看更多
登录 后发表回答