我正试图编写一个非常简单的程序,用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() 否则你什么也看不到。
pexpect.spawn()
# for Python 2 child.logfile_read = sys.stdout # for Python 3 child.logfile_read = sys.stdout.buffer
最后还需要以下语句(否则脚本将在 sendline('touch foo') touch foo 没有机会运行):
sendline('touch foo')
touch foo
child.sendline('exit') child.expect(pexpect.EOF)
根据手册:
logfile_read 和 logfile_send 成员可用于分别记录来自子级的输入和发送给子级的输出。有时你不想看到你写给孩子的每一件事。您只想记录孩子发回的内容。例如: child = pexpect.spawn('some_command') child.logfile_read = sys.stdout
logfile_read 和 logfile_send 成员可用于分别记录来自子级的输入和发送给子级的输出。有时你不想看到你写给孩子的每一件事。您只想记录孩子发回的内容。例如:
logfile_read
logfile_send
child = pexpect.spawn('some_command') child.logfile_read = sys.stdout