不鼓励从Python脚本调用Windows命令行吗?

时间:2019-10-14 13:37:25

标签: python python-3.x windows cmd

与运行具有等效功能的Python代码相比,从Python脚本调用Windows cmd有什么弊端?

我的代码如下:

import subprocess
def runWinCmd(cmd):
    result = []
    process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    for line in process.stdout:
        result.append(line)

    errcode = process.returncode

    return errcode

2 个答案:

答案 0 :(得分:2)

subprocess.call("exit 1", shell=True)

参数shell=True不能构成安全隐患。

来自docs

  

警告:使用shell = True可能会带来安全隐患。有关详细信息,请参见“常用参数”下的警告。

More

  

警告:执行包含来自不受信任源的未经处理的输入的shell命令会使程序容易受到shell注入的攻击,这是一个严重的安全缺陷,可能导致任意命令执行。因此,在从外部输入构造命令字符串的情况下,强烈建议不要使用shell = True:

一个例子:

>>> from subprocess import call
>>> filename = input("What file would you like to display?\n")
What file would you like to display?
non_existent; rm -r dir1 / #  {delete something -- like a directory} 
>>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...

答案 1 :(得分:-3)

您还可以使用lib中的构建。参见os.system()