Difference between shell=True or False in python subprocess [duplicate]

百般思念 提交于 2021-02-09 14:36:33

问题


I just started working with python subprocess module.

The code subprocess.call("ls", shell = False) and subprocess.call("ls", shell = True) both return the same results. I just want to know what is the main difference between the two shell options.


回答1:


Straight out of the Docs:

If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user’s home directory. However, note that Python itself offers implementations of many shell-like features (in particular, glob, fnmatch, os.walk(), os.path.expandvars(), os.path.expanduser(), and shutil).

This can open your code to shell injection techniques which can be better explained here:

Shell Injection Shell=True

On a windows machine for example, if shell was set as false, see below:

import subprocess

subprocess.Popen("dir", shell = False)

When run this code shall return a WindowsError: [Error 2] stating that the specified file can not be found. However if shell is True, an object shall be returned. This is because 'dir' is being 'piped' through cmd, and therefore, builtin commands such as dir will work.

The same works with subprocess.call.



来源:https://stackoverflow.com/questions/38408908/difference-between-shell-true-or-false-in-python-subprocess

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