Simplest way to run an Expect script from Python

烂漫一生 提交于 2019-12-17 18:30:33

问题


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?


回答1:


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

Example:

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 comes with lots of examples to learn from. For use of interact(), check out script.py from examples:

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

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

  • Can I use Expect on Windows without installing Cygwin?



回答2:


Since it is an .expect script, I think you should change the extend name of your script.

Instead of using

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

you should use

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


来源:https://stackoverflow.com/questions/11160504/simplest-way-to-run-an-expect-script-from-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!