pexpect ssh无法处理命令选项
我正在使用pexpect ssh来编写一个编译脚本,ssh自动化的样子是这样的,
enter code here
child = ssh_expect('root', server2, cmd)
child.expect(pexpect.EOF)
print child.before
其中cmd是这个:
cmd = "./configure CFLAGS=\"-g -O0 -DDEBUG\""
问题出现在这里,它显示,
configure: error: unrecognized option: -O0
而如果我用commands.getoutput来运行相同的命令,它就能正常执行。
请问是什么原因导致这种错误出现,我该如何解决这个问题呢?
提前谢谢你们 :)
1 个回答
0
之所以在使用 commands.getoutput
时能正常工作,是因为所有命令都是通过一个“壳”(shell)来运行的,这个壳会解析你的命令行,并理解在 CFLAGS 后面双引号里的内容是同一个参数的一部分。
而当你通过 pexpect 运行命令时,就没有这个“壳”了。此外,在通过 ssh 连接时,你在 ssh 命令行上提供的命令也没有“壳”来处理,所以没有东西能把 CFLAGS 解析成一个参数。因此,configure 脚本得到的不是一个参数(CFLAGS=\"-g -O0 -DDEBUG\"),而是三个参数('CFLAGS=-g', '-O0', '-DDEBUG')。
如果可以的话,尽量避免发送参数之间用空格分开的命令。看起来 pexpect 可以接受一个参数列表。下面是一个有效的代码示例:
#/usr/bin/env python
import pexpect
def ssh_expect(user, hostname, cmd):
child = pexpect.spawn("ssh", ["%s@%s" % (user, hostname)] + cmd, timeout=3600)
return child
child = ssh_expect("root", "server.example.com", ["./configure", "CFLAGS=\"-g -O0 -DDEBUG\""])
child.expect(pexpect.EOF)
print child.before