9

我正在尝试指示我的 Python 安装执行Expect脚本“myexpect.sh”:

#!/usr/bin/expect
spawn ssh usr@myip
expect "password:"
send "mypassword\n";
send "./mycommand1\r"
send "./mycommand2\r"
interact

我在 Windows 上,因此无法将 Expect 脚本中的行重写为 Python。有什么建议么?有什么东西可以像“./myexpect.sh”那样从 bash shell 运行吗?


我使用 subprocess 命令取得了一些成功:

subprocess.call("myexpect.sh",  shell=True)

我收到错误:

myexpect.sh 不是有效的 Win32 应用程序。

我该如何解决这个问题?

4

2 回答 2

23

使用pexpect 库。这是 Expect 功能的 Python 版本。

例子:

child = pexpect.spawn('Some command that requires password')
child.expect('Enter password:')
child.sendline('password')
child.expect(pexpect.EOF, timeout=None)
cmd_show_data = child.before
cmd_output = cmd_show_data.split('\r\n')
for data in cmd_output:
    print data

Pexpect 提供了许多可供学习的示例。要使用 interact(),请查看script.py示例:

(对于 Windows,有 pexpect 的替代方法。)

于 2012-06-22T16:41:54.860 回答
0

由于它是一个 .expect 脚本,我认为您应该更改脚本的扩展名。

而不是使用

subprocess.call("myexpect.sh", shell=True)

你应该使用

subprocess.call("myexpect.expect", shell=True)
于 2018-02-28T20:17:19.287 回答