从Python运行Expect脚本的最简单方法

从Python运行Expect脚本的最简单方法

问题描述:

我正试图指示我的Python安装程序执行期望脚本"myexpect. sh":

I'm trying to instruct my Python installation to execute an Expect script "myexpect.sh":

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

我在Windows上,因此不能将Expect脚本中的行重写为Python.有什么建议?有什么可以从bash shell中以"./myexpect.sh"的方式运行它的吗?

I'm on Windows so re-writing the lines in the Expect script into Python are not an option. Any suggestions? Is there anything that can run it the way "./myexpect.sh" does from a bash shell?

我在subprocess命令上取得了一些成功:

I have had some success with the subprocess command:

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

我收到错误:

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

myexpect.sh is not a valid Win32 application.

我该如何解决?

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

Use the pexpect library. This is the Python version for Expect functionality.

示例:

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:

Pexpect comes with lots of examples to learn from. For use of interact(), check out script.py from examples:

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

(For Windows, there is an alternative to pexpect.)