This evil:
p = subprocess.Popen('unrar e ' + root + '/' + i + ' ' + testfolder, bufsize=2048, shell=True, stdin=subprocess.PIPE)
Instead of this
p = subprocess.Popen(['unrar', 'e', '%s/%s' % (root, i), testfolder], bufsize=2048, stdin=subprocess.PIPE) p.stdin.write('e') p.wait() if p.returncode == 0: pass # put code that must only run if successful here.
By Popen exact array, not a string, to Popen and not using shell=True , a file name with a space in it cannot be interpreted as more than one argument or a subshell command or some other potentially malicious one (think of a file with $(rm -rf ..) in his name).
Then after calling p.wait() (there is no need for p.communicate() when you are not doing stderr or stdout), you should check p.returncode to determine if the process was successful, and only continue deleting files if p.returncode == 0 (indicating success).
An initial diagnosis that p.communicate() returns while the unrar process is still running is not possible; p.communicate() and p.wait() do not work.
If you use ssh , this will change a bit:
import pipes
source share