如何以 root 身份执行 os.* 方法? [英] How to execute os.* methods as root?

查看:53
本文介绍了如何以 root 身份执行 os.* 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不存储在我的脚本内存中的情况下请求 root pw 并以 root 身份运行一些 os.* 命令?

Is it possible to ask for a root pw without storing in in my script memory and to run some of os.* commands as root?

我的剧本

  1. 扫描一些文件夹和文件以检查它是否可以完成这项工作
  2. 在/etc/... 中进行了一些更改
  3. 创建一个文件夹和文件,这些文件应该归运行脚本的用户所有

(1) 可以作为普通用户完成.我可以通过 sudo 脚本来执行 (2),但是 (3) 中的文件夹和文件将是 root 的.

(1) can be done as a normal user. I can do (2) by sudoing the script, but then the folder and files in (3) will be root's.

问题是我使用了很多 os.makedirs、os.symlink 等,这让我无法让普通用户运行它.

The issue is that I use a lot of os.makedirs, os.symlink, etc, which stops me from making it runnable by a normal user.

Tanks 2 all 的建议

目前的解决方案是:

# do all in sudo
os.chown(folder, int(os.getenv('SUDO_UID')), int(os.getenv('SUDO_GID')))

感谢 gnibbler 的提示.

推荐答案

gnibbler 提示了 os.chown.然后问题是要知道 sudo 背后的用户的 ID.该信息存储在环境变量 SUDO_* 中:

gnibbler gave a hint at os.chown. The problem was then to know the ID of the user behind sudo. That information is stored in environment variables SUDO_*:

os.chown, (some_path, int(os.getenv('SUDO_UID')), int(os.getenv('SUDO_GID')))

将代码分成 3 个文件可能是一个解决方案,但是代码已经混合了,所以不合适.

Splitting the code in 3 files could be a solution, but the code is already mixed, so that's not suitable.

这篇关于如何以 root 身份执行 os.* 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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