从Python运行Expect脚本的最简单方法 [英] Simplest way to run an Expect script from Python

查看:777
本文介绍了从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.)

这篇关于从Python运行Expect脚本的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆