使用 expect 从 ssh 获取输出

Using expect to get output from ssh

我正在尝试使用 expect 将任务作为更大的 python 程序的一部分自动执行,但在获取 ssh 命令的标准输出 运行 时遇到了很多麻烦在远程机器上。我以前没有使用过 expect,也没有在手册页上成功找到解决方案。

在实际能够 运行 这个命令之前,我需要使用 expect 来自动化一些交互,但我在这里删除了它们以简化问题。

这是程序的简化示例:

import subprocess

expect = """
/usr/bin/expect <<EOF

spawn ssh some_machine ls
expect eof
puts "$expect_out(buffer)"
"""

output = subprocess.check_output(expect, shell=True)
print(output)

输出:

b'spawn ssh some_machine ls\r\n116029\r\nArchive\r\n\r\n(buffer)\n'

它似乎包含生成命令以及末尾的“(buffer)”。我不确定为什么会这样。我试图只获得 ls.

的结果

如果我在 expect 中打开调试模式,我看到 expect_out(buffer) 被设置为我想要的 return,但是 puts 没有反映这一点。

输出:

expect version 5.45
argv[0] = /usr/bin/expect  argv[1] = -d
set argc 0
set argv0 "/usr/bin/expect"
set argv ""
executing commands from command file
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {1753}
expect: read eof
expect: set expect_out(spawn_id) "exp7"
expect: set expect_out(buffer) "116029\r\nArchive\r\n"
<wrong output as above>

您可以使用 log_user 命令抑制 expect 的日志输出:

log_user 0
spawn ssh some_host ls
expect eof
puts "$expect_out(buffer)"

没有 log_user 0,我得到:

$ expect -f sample.tcl
spawn ssh some_host ls
file1
file2

通过添加 log_user 0,我得到:

$ expect -f sample.tcl
file1
file2

当您通过标准输入输入 expect 脚本时似乎有些奇怪,但以下似乎有效:

import subprocess
import tempfile

expect = """
log_user 0
spawn ssh some_host ls < /dev/null
expect eof
puts "$expect_out(buffer)"
"""

with tempfile.NamedTemporaryFile() as fd:
    fd.write(expect)
    fd.flush()
    fd.seek(0)
    output = subprocess.check_output(['expect', fd.name])

print(output)