系统未响应预期命令

System not responding to pexpect commands

我正在尝试编写非常简单的程序来使用 pexpect 控制远程机器。但是远程系统对发送的命令没有反应。

这里是源代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pexpect
import sys
child = pexpect.spawn('telnet 192.168.2.81 24')
res = child.expect('/ # ')
print(res)
res = child.sendline('touch foo')
print(res)

这是输出:

0
10

因此,据我了解,命令执行成功但在目标系统上没有结果,即未创建 foo 文件。

有人可以帮我吗?

pexpect.spawn() 之后添加以下行,否则您什么也看不到。

# for Python 2
child.logfile_read = sys.stdout

# for Python 3
child.logfile_read = sys.stdout.buffer

你还需要在最后添加以下语句(否则脚本会在 sendline('touch foo') 后立即退出,因此 touch foo 没有机会 运行):

child.sendline('exit')
child.expect(pexpect.EOF)

根据手册:

The logfile_read and logfile_send members can be used to separately log the input from the child and output sent to the child. Sometimes you don’t want to see everything you write to the child. You only want to log what the child sends back. For example:

child = pexpect.spawn('some_command')
child.logfile_read = sys.stdout