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.