【问题标题】:invoke os.system as a non-root user in a root-user launched python program在 root 用户启动的 python 程序中以非 root 用户身份调用 os.system
【发布时间】:2020-07-26 22:44:56
【问题描述】:

我想使用 sudo(例如 sudo python test.py)运行 python 程序,但是在 python 程序中,当我使用 os.system(<some command>) 调用其他进程时,我想以非 root 用户身份运行它们。

这可行吗?

谢谢!

【问题讨论】:

  • 分叉一个子进程。在子流程中,给用户打电话os.setuid(),然后做你想做的事。在父进程中,等待子进程完成 (os.waitpid())。
  • @alaniwi 谢谢!这行得通!我刚刚发现的另一种方法似乎是我可以在要运行的命令前面添加前缀“sudo -u username”以作为该特定用户执行。
  • 能否将您找到的解决方案添加为问题的正确答案。这可能对其他人有所帮助。

标签: python linux


【解决方案1】:

例子:

import os
import pwd

username = "nobody"

pwent = pwd.getpwnam(username)
uid = pwent.pw_uid
gid = pwent.pw_gid

pid = os.fork()
if pid == 0:
    # child

    # relinquish any privileged groups before we call setuid
    # (not bothering to load the target user's supplementary groups here)
    os.setgid(gid)
    os.setgroups([])

    # now relinquish root privs
    os.setuid(uid)

    # os.setuid should probably raise an exception if it fails,
    # but I'm paranoid so...
    if os.getuid() != uid:
        print("setuid failed - bailing")
        os._exit(1)

    return_value = os.system("id") // 256  # or whatever
    os._exit(return_value)

# parent
os.waitpid(pid, 0)

print("parent continues (still root here)")

os.system("id")

给予:

uid=65534(nobody) gid=65534(nogroup) groups=65534(nogroup)
parent continues (still root here)
uid=0(root) gid=0(root) groups=0(root)

【讨论】:

    【解决方案2】:

    另一种方法是在要以特定用户身份运行的命令前添加前缀sudo -u username。例如,可以使用os.system('sudo -u user_a python test.py') 在python 脚本中以user_a 运行test.py

    【讨论】:

      猜你喜欢
      • 2015-04-29
      • 2015-09-25
      • 2018-04-09
      • 2021-12-27
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      相关资源
      最近更新 更多