我使用 subprocess.popen()
函数来执行 Python 命令,代码如下:
omp_cmd = 'cat %s | omp -h %s -u %s -w %s -p %s -X -' %(temp_xml, self.host_IP, self.username, self.password, self.port)
xmlResult = Popen(omp_cmd, stdout=PIPE, stderr=STDOUT)
在shell中它能够正常运行,但在Python中会出错:
File "/home/project/vrm/apps/audit/models.py", line 148, in sendOMP
xmlResult = Popen(omp_cmd, stdout=PIPE, stderr=STDOUT)
File "/usr/local/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/local/lib/python2.7/subprocess.py", line 1228, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
我在搜索这个错误,但是没有解决我的问题。有人知道这个问题的原因吗?
shell=False
时,参数通常是一个列表。我使用了shlex.split
函数,该函数将字符串分割成列表,就像典型的shell一样。当使用shell=True
时,你传递一个字符串,该字符串由shell进行评估。当使用shell=False
时,你可以传递一个字符串或者一个列表。如果传递一个字符串,则它被视为唯一的命令。("ls -l"
将会失败,因为没有ls -l
这个命令,只有ls
)。如果传递一个列表,则将每个元素作为一个参数。["ls", "-l"]
- mgilsoncat
的依赖,因此无需使用shell=True
。shell=True
的问题在于,如果给出不受信任的输入,它容易受到shell注入攻击。(比如说,如果self.host_IP
被分配了值"; rm -rf ~;"
) - mgilson