python - 系统不响应 pexpect 命令

标签 python networking pexpect

我正在尝试编写非常简单的程序,使用 pexpect 控制远程计算机。但远程系统不会对发送的命令使用react。

这是源代码:

#!/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

关于python - 系统不响应 pexpect 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47032456/

相关文章:

python - 将数据分配给 for 循环中的现有列

python - 处理 pandas Dataframe 中的特殊字符作为列名

python - 如何使用 python 让 selenium 同时按下 Shift + Enter 键盘?

docker - docker daemon 在部署 compose 环境时用完要分配的网络 IP 地址时会发生什么?

java - MacOS 中 docker 上的 Wildfly Swarm

python - Elixir 的 Pylons

java - SocketChannel.close() 是否也关闭套接字?

python - 如何捕获子进程的输入和输出?

Python pexpect - TIMEOUT 陷入回溯并退出

python - 使用子进程模块通过 SSH 连接 Linux 盒子