When we execute a subprocess such as the follows:

sub_ret = subprocess.Popen(args,stdout=subprocess.PIPE,shell=True)

This poses a security risk as it allows malicious users to inject commands via the args parameter.

Would it be safer to use with the shell as false? Such as:

sub_ret = subprocess.Popen(args,stdout=subprocess.PIPE,shell=False)

Or would this pose a security risk as well?


The major difference is the way you construct your commands:

subprocess.Popen("ls -l /tmp", shell=True)


subprocess.Popen(['ls', '-l','/tmp'])

The first example is one string and works with shell set to true, the second example is without. This requires each part of the command to be passed as a seperate item in the array. The danger is when you accept part of the command as input from an untrusted source.

For instance if you would accept part of the command from a user, in the first example he can literally type any command he wants, whereas in the latter example he can only define on parameter or destination. Adding more commands will not be possible as subprocess will fail (providing you do not construct the array based on the user input, but just accept one argument for a specific position).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.