pexpect ssh 无法处理命令选项

发布于 2024-11-25 18:16:42 字数 460 浏览 3 评论 0原文

我正在使用 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运行相同的命令,那么它会正确执行。

问题是产生这种错误的问题是什么?我该如何消除这个错误?

提前致谢 :)

am using pexpect ssh to write down a script for compilation, the ssh automation looks like this,

enter code here
child = ssh_expect('root', server2, cmd)
child.expect(pexpect.EOF)
print child.before

where cmd is this:

cmd = "./configure CFLAGS=\"-g -O0 -DDEBUG\""

the problem happens is that it says,

configure: error: unrecognized option: -O0

whereas, if run the same command using commands.getoutput then it executes properly.

Question what is the problem that this kind of error is getting generated and how can I erradicate this one?

thanks in advance :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱格式化 2024-12-02 18:16:42

如果您正在执行commands.getoutput,它起作用的原因是所有命令都通过shell运行,shell将解析您的命令行并了解CFLAGS之后的双引号之间的内容是相同的一部分范围。

当您通过 pexpect 运行 cmd 时,不涉及 shell。此外,当您在 ssh 命令行上提供命令时,ssh 连接的另一端不涉及 shell,因此没有任何内容可以将 CFLAGS 解析为一个参数。因此,配置脚本不是获取一个参数 (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

The reason it's working if you're doing commands.getoutput is that all commands there are run though a shell, which will parse your commandline and understand that what's between the double quotes after CFLAGS is part of the same parameter.

When you're running cmds through pexpect, no shell is involved. Also, there's no shell involved on the other side of the ssh connection when you provide commands on the ssh commandline, so there's nothing that parse CFLAGS into one parameter. Therefore, instead of the configure script getting one parameter (CFLAGS=\"-g -O0 -DDEBUG\"), it gets three parameters ('CFLAGS=-g', '-O0', '-DDEBUG').

If possible, avoid sending commands where parameters are separated by spaces. It seems pexpect can take a list of arguments instead. Working code example:

#/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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文