如果使用 sudo 运行调用脚本,python 子进程 Popen 会调用“继承"根权限吗? [英] Will a python subprocess Popen call 'inherit' root privs if the calling script is run with sudo?

查看:51
本文介绍了如果使用 sudo 运行调用脚本,python 子进程 Popen 会调用“继承"根权限吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 python 脚本,它将使用子进程 Popen(我正在考虑使用通信())来运行各种 shell 命令等.通常,我正在执行的 shell 命令通常会(手动)使用 sudo 运行.

I am writing a python script that will use subprocess Popen (with communicate() I am thinking) to run various shell commands, etc. Often, the shell commands that I am executing would typically be run (manually) with sudo.

我正在运行使用带有 sudo 的子进程的脚本.我想知道我是否可以安全地将 sudo 从我的所有子进程调用中删除,或者我是否需要包含它并使用 stdin 来提供密码.

I am running the script that uses subprocess with sudo. I am wondering if I can safely leave sudo off all of my subprocess calls or if I need to include it and use stdin to provide a password.

这似乎是一个非常简单的问题,但我一直无法找到答案.从我的实验来看,似乎我可能不需要 sudo,但我不确定这是否真的如此,或者它是否只是以这种方式工作",因为我最近提供了我的密码.

This seems like a pretty simple question, but I have been unable to find the answer yet. From my experimentation, it seems like I might not need to sudo, but I am not sure if that is really true or if it is simply 'working this way' because I have recently provided my password.

我想出了如何删除和恢复 root 的方法.使用多处理包非常简单

I figured out how to drop and recover root. Its pretty simple with the multiprocessing package

...
from multiprocessing import Process, Pipe
...
parent_conn, child_conn = Pipe()
p = P(input_list, child_conn)
p.start()
p.join()
return RunSyncReturn(**parent_conn.recv())
...

class P(Process):
    def __init__(self, input_list, conn):
        super(P, self).__init__()
        self._input_list = input_list
        self._conn = conn

    def run(self):
        drop_privileges()
        process = Popen(self._input_list, stdout=PIPE)
        stdout, stderr = process.communicate()
        pmap = {}
        pmap['stdout'] = stdout
        pmap['stderr'] = stderr
        pmap['exit_code'] = process.returncode
        self._conn.send(pmap)
        self._conn.close()

RunSyncReturn 只是一个数据持有者类.当使用 multiprocessing Process 类启动的 Process 终止时,降低的权限也会随之消失.

RunSyncReturn is just a data holder class. When the Process launched with the multiprocessing Process class dies, the lowered privileges go away with it.

推荐答案

用户 ID 和访问权限将被子进程继承.只要您运行的所有命令都不是由其他用户拥有并且设置了 s 位,它们也将以 root 身份运行.

User IDs and access rights will get inherited by subprocesses. As long as none of the commands you're running is owned by a different user and has the s-bit set, they will run as root as well.

这篇关于如果使用 sudo 运行调用脚本,python 子进程 Popen 会调用“继承"根权限吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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