从运行的Python的Expect脚本的最简单方法(Simplest way to run an E

2019-06-25 17:03发布

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

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?


I have had some success with the subprocess command:

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

I receive the error:

myexpect.sh is not a valid Win32 application.

How do I get around this?

Answer 1:

使用Pexpect的库 。 这是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的带有大量的例子可以借鉴。 对于使用交互()的,看看script.py从例子:

  • https://github.com/pexpect/pexpect/tree/master/examples

(对于Windows,存在要Pexpect的一种替代方法。)

  • 我可以使用预计在Windows上没有安装Cygwin?


Answer 2:

因为它是一个.expect剧本,我想你应该改变你的脚本的扩展名。

而不是使用

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

你应该使用

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


文章来源: Simplest way to run an Expect script from Python