Python subprocess stdin=PIPE security - python

How "secure" is it to launch a subprocess with root privileges and attach stdin on that subprocess to PIPE on the parent process?
I'm writing a python program where the majority of its functions can run fine as the normal user, but there are some functions that require root. Rather than make the user run the whole, big GUI application as root, I'm spawning a subprocess with root privileges.
proc = subprocess.Popen(
['/usr/bin/osascript', '-e', 'do shell script "./root_child.py" with administrator privileges'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE
)
I need that subprocess to run in the background constantly with a minimal set of functions that can do very powerful, destructive things. When the parent process needs it, it will communicate to the subprocess via the subprocess.PIPE -> stdin on the child process.
I'm asking because I want to make sure that no other process can communicate to the this child process other than its parent process.
What measures does python and/or the OS take to ensure that a subprocess's stdin can only be written-to by its parent process? And if that's not done by default, how can I make it so that the child process's stdin can only be written-to by its parent process?

Related

calling shell script from python where shell connects to database

I want to call shell script from python code. The shell script which I am trying to call is having multiple database (DB2) call in it; means it connects to DB2 database multiple times and execute different database sqls. I tried using subprocess.call method like (subprocess.call(['./<shell script with full path>'])); but it seems before the script connects to database and executes the commands mentioned within the script, it is terminating. But when I am calling the shell script as a standalone script from command line, then it is working good.
Is there any other way this can be handled?
subprocess: The subprocess module allows you to spawn new processes,
connect to their input/output/error pipes, and obtain their return
codes.
http://docs.python.org/library/subprocess.html
Usage:
import subprocess
process = subprocess.Popen(command, shell=True)
process.wait()
print process.returncode
Side note: It is best practice to avoid using shell=True as it is a security hazard.
Actual meaning of 'shell=True' in subprocess

How can I start a subprocess in Python that runs independently and continues running if the main process is closed?

I have a small Flask API that is receiving requests from a remote server. Whenever a request is received, a subprocess is started. This subprocess is simply executing a second Python file that is in the same folder. This subprocess can run for several hours and several of these subprocesses can run simultaneously. I am using stdout to write the output of the python file into a text file.
All of this is working fine, but every couple of weeks it happens that the Flask API becomes unresponsive and needs to be restarted. As soon as I stop the Flask server, all running subprocesses stop. I would like to avoid this and run each subprocess independently from the flask API.
This is a small example that illustrates what I am doing (this code is basically inside a method that can be called through the API)
import subprocess
f = open("log.txt","wb")
subprocess.Popen(["python","job.py"],cwd = "./", stdout = f, stderr = f)
I would like to achieve that the subprocess keeps running after I stop the Flask API. This is currently not the case. Somewhere else I read that the reason is that I am using the stdout and stderr parameters, but even after removing those the behavior stays the same.
Any help would be appreciated.
Your sub-processes stop because their parent process dies when you restart your Flask server. You need to completely separate your sub-processes from your Flask process by running your Python call in a new shell:
from subprocess import call
# On Linux:
command = 'gnome-terminal -x bash -l -c "python job.py"'
# On Windows:
# command = 'cmd /c "python job.py"'
call(command, shell=True)
This way your Python call of job.py will run in a separate terminal window, unaffected by your Flask server process.
Use fork() to create a child process of the process in which you are calling this function. On successful fork(), it returns a zero for the child id.
Below is a basic example of fork, which you can easily incorporate in your code.
import os
pid = os.fork()
if pid == 0: # new process
os.system("nohup python ./job.py &")
Hope this helps!

Python kill parent script (subprocess)

Im working on two scripts.
One script is perpetually running.
When it senses an update to itself, it will run the second script as a subprocess.
The second script should kill the first script, implement the changes and run the updated script.
However, I cant find a way to kill the first script. How does the child process kill its parent?
You are doing this backwards, and shouldn't be using the child process to kill the parent process.
Instead, you will want a parent process of your "perpetually running" script (which will now be the subprocess). When an update is detected, the subprocess kills itself, and requests that the parent implement your changes. The parent will then restart the subprocess.

Popen new process group on linux

I am spawning some processes with Popen (Python 2.7, with Shell=True) and then sending SIGINT to them. It appears that the process group leader is actually the Python process, so sending SIGINT to the PID returned by Popen, which is the PID of bash, doesn't do anything.
So, is there a way to make Popen create a new process group? I can see that there is a flag called subprocess.CREATE_NEW_PROCESS_GROUP, but it is only for Windows.
I'm actually upgrading some legacy scripts which were running with Python2.6 and it seems for Python2.6 the default behavior is what I want (i.e. a new process group when I do Popen).
bash does not handle signals while waiting for your foreground child process to complete. This is why sending it SIGINT does not do anything. This behaviour has nothing to do with process groups.
There are a couple of options to let your child process receive your SIGINT:
When spawning a new process with Shell=True try prepending exec to the front of your command line, so that bash gets replaced with your child process.
When spawning a new process with Shell=True append the command line with & wait %-. This will cause bash to react to signals while waiting for your child process to complete. But it won't forward the signal to your child process.
Use Shell=False and specify full paths to your child executables.

Kill Windows asynchronous Popen process in 2.4

I have a testing script that needs to open a process (a Pyro server), do some stuff that will call the opened process for information, and when it's all done will need to close the process back down. It's all part of an automated test on a staging server.
In python 2.6 you can do this:
pyro_server = subprocess.Popen(['python', 'pyro_server.py'])
# Do stuff, making remote calls to the Pyro server on occasion
pyro_server.terminate()
Alas, I'm locked into python 2.4 here at work so I don't have access to that function. And if I just let the script end of course the server lives on. What should I be doing to close/kill that process before the script exits?
Consider copying subprocess.py to your python2.4 dist-packages directory. It should just work as it's a simple wrapper around the old popen library.
The Popen object terminate function does nothing more than the following:
import os, signal
os.kill(pid, signal.SIGKILL)
pid is the child process's process id. signal.SIGKILL is the number 9, and is a standard unix kill signal. You can see how to spawn a subprocess and get its pid in python 2.4 with the popen module here:
#BrainCore: Note that os.kill is not available on windows in python24, check the docs.
My solution for killing a subprocess.Popen object on windows when using python24 is this:
import os, subprocess
p = subprocess.Popen(...)
res = os.system('taskkill /PID %d /F' % p.pid)

Categories