Python 禁用和启用根权限 [英] Python Disable and Enable Root Privileges

查看:66
本文介绍了Python 禁用和启用根权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

尝试以下操作:

导入操作系统打印执行代码的用户:%d"% os.getuid()打印当前有效用户:%d"% os.geteuid()如果 os.getuid() == 0:os.seteuid(65534) # 用户nobody"的用户ID打印当前有效用户:%d"% os.geteuid()# 在此处使用非 root 权限执行您需要执行的操作,例如写入文件打印 >>open("/tmp/foobar.txt", "w"), "hello world"os.seteuid(0)打印当前有效用户:%d"% os.geteuid()

将此作为根输出运行:

<前>执行代码的用户:0当前有效用户:0当前有效用户:65534当前有效用户:0

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?

解决方案

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

这篇关于Python 禁用和启用根权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆