亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

詳談python中subprocess shell=False與shell=True的區別

瀏覽:2日期:2022-06-21 15:19:51

shell=True參數會讓subprocess.call接受字符串類型的變量作為命令,并調用shell去執行這個字符串,當shell=False是,subprocess.call只接受數組變量作為命令,并將數組的第一個元素作為命令,剩下的全部作為該命令的參數。

舉個例子來說明

詳談python中subprocess shell=False與shell=True的區別

from subprocess import call import shlex cmd = 'cat test.txt; rm test.txt' call(cmd, shell=True)

上述腳本中,shell=True的設置,最終效果是執行了兩個命令

cat test.txt 和 rm test.txt

把shell=True 改為False,

from subprocess import call import shlex cmd = 'cat test.txt; rm test.txt' cmd = shlex(cmd) call(cmd, shell=False)

則調用call的時候,只會執行cat的命令,且把 'test.txt;' 'rm' 'test.txt' 三個字符串當作cat的參數,所以并不是我們直觀看到的好像有兩個shell命令了。

也許你會說,shell=True 不是很好嗎,執行兩個命令就是我期望的呀。但其實,這種做法是不安全的,因為多個命令用分號隔開,萬一檢查不夠仔細,執行了危險的命令比如 rm -rf / 這種那后果會非常嚴重,而使用shell=False就可以避免這種風險。

總體來說

看實際需要而定,官方的推薦是盡量不要設置shell=True。

補充: 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). 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.

對于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攻擊:

from subprocess import callfilename = input('What file would you like to display?n')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。

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。如有錯誤或未考慮完全的地方,望不吝賜教。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 99久久免费精品 | 亚洲久草视频 | 亚洲视频2020 | 久久六月丁香婷婷婷 | 轻轻啪在线视频播放 | 最新亚洲手机在线人成网站 | 亚洲国产精品ⅴa在线观看 亚洲国产精品aaa一区 | 欧美一区二区精品系列在线观看 | 狠狠久久综合 | 人人干人人插 | 在线视频精品视频 | 日本三级黄色 | 色偷偷尼玛图亚洲综合 | 手机看片福利日韩欧美看片 | 亚洲欧美日韩中文在线制服 | 欧美成人午夜 | 嘿咻18视频在线看 | 日韩欧美影视 | 亚洲精品国产第一区二区图片 | 亚洲精品一区二区三区国产 | 国内精品久久久久久麻豆 | 黄色在线不卡 | 亚洲欧洲国产视频 | 国产亚洲精品久久麻豆 | 99热在线获取最新地址 | 免费三级黄色 | 久久久免费精品 | 国产免费播放一区二区 | 国产三级毛片 | 国产成人啪午夜精品网站男同 | 国产亚洲人成网站观看 | 轻轻碰在线视频免费视频 | 精品九九九 | 日本二级黄色片 | 国产精品美女免费视频大全 | 免费国产一级特黄aa大 | 国产精品久久福利网站 | 国自产在线精品免费 | 美女大片高清特黄a大片 | 亚洲一级毛片免费看 | 国产精品久久久久久吹潮 |