Will a python subprocess Popen call 'inherit' root privs if the calling script is run with sudo?

时光怂恿深爱的人放手 提交于 2019-12-25 02:19:46

问题


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.

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.

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.

EDIT: 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 is just a data holder class. When the Process launched with the multiprocessing Process class dies, the lowered privileges go away with it.


回答1:


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.




回答2:


I was hoping to do this: change_privileges(); do_something(); change_privileges('root', 'root')

Instead of trying temporarily to change privileges in the same process, use prexec_fn function to drop privileges only for the child process started by Popen() e.g., look at demote() function.



来源:https://stackoverflow.com/questions/22233454/will-a-python-subprocess-popen-call-inherit-root-privs-if-the-calling-script-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!