为Python中的某些操作放弃root特权 [英] Drop root privileges for certain operations in Python

查看:104
本文介绍了为Python中的某些操作放弃root特权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Python脚本中,我执行一些需要root特权的操作.我还创建并写入不希望由root用户而是运行我的脚本的用户专有的文件.

In my Python script, I perform a few operations that need root privileges. I also create and write to files that I don't want to be owned exclusively by root but by the user who is running my script.

通常,我使用sudo运行脚本.有没有办法做上面的事情?

Usually, I run my script using sudo. Is there a way to do the above?

推荐答案

您可以使用os.seteuid()在uid之间切换.这与os.setuid()的不同之处在于,您可以在需要root特权时返回到该特权.

You can switch between uid's using os.seteuid(). This differs from os.setuid() in that you can go back to getting root privileges when you need them.

例如,以超级用户身份运行以下命令:

For example, run the following as root:

import os

open('file1', 'wc')

# switch to userid 501
os.seteuid(501)
open('file2', 'wc')

# switch back to root
os.seteuid(0)
open('file3', 'wc')

这将以根身份创建file1file3,但以uid 501用户身份创建file2.

This creates file1 and file3 as root, but file2 as the user with uid 501.

如果要确定哪个用户正在调用脚本,sudo设置两个环境变量:

If you want to determine which user is calling your script, sudo sets two environment variables:

SUDO_USER
SUDO_UID

分别调用sudo的用户名和uid.因此,您可以使用int(os.environ['SUDO_UID'])os.seteuid()一起使用.

Respectively the username and the uid of the user who called sudo. So you could use int(os.environ['SUDO_UID']) to use with os.seteuid().

这篇关于为Python中的某些操作放弃root特权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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