从 Python 运行 Expect 脚本的最简单方法 [英] Simplest way to run an Expect script from Python
问题描述
我正在尝试指示我的 Python 安装执行 Expect 脚本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
";
send "./mycommand1
"
send "./mycommand2
"
interact
我使用的是 Windows,因此无法将 Expect 脚本中的行重写为 Python.有什么建议?有没有什么东西可以像./myexpect.sh"那样从 bash shell 运行它?
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.
我该如何解决这个问题?
How do I get around this?
推荐答案
使用 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('
')
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屋!