Python禁用并启用根权限

时间:2012-11-06 06:08:35

标签: python root

我有一段代码,我想以非root身份运行。如果程序以非root身份运行,则不需要执行任何操作。但是如果程序以root身份运行,则需要删除root权限,执行代码段,然后再次启用root权限。你如何为启用/禁用编写代码?

2 个答案:

答案 0 :(得分:0)

尝试os.getuid()os.setuid()。您可以使用它们在脚本中切换用户。

答案 1 :(得分:0)

尝试以下方法:

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()

以root输出方式运行:

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