天天看點

python subprocess子產品的shell參數問題

昨天調試其他同學的代碼時,發現對于subprocess子產品所傳的args變量,與shell變量存在關聯,傳值不當會有各種問題。比較有趣,就記錄一下。

根據subprocess子產品的args定義如下:

args is required for all calls and should be a string, or a sequence of program arguments. providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). <code>if passing a single string, either shell must be true (see below) or else the string must simply name the program to be executed without specifying any arguments.</code>

</blockquote>

對于args,可傳string,也可傳list,但當傳string時,shell的值必須設為true。

當shell為true時

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.

就是調用了系統的 sh 來執行指令(args的string),這樣會導緻一些猥瑣的安全問題,類似于sql injection攻擊:

what file would you like to display?

non_existent; rm -rf / #

call("cat " + filename, shell=true) # uh-oh. this will end badly...

是以,安心用shell=false吧,記得args傳list。