Skip to main content
 首页 » 编程设计

Python 禁用和启用根权限

2025年05月04日13mfrbuaa

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

请您参考如下方法:

尝试以下操作:

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

以根输出运行:

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