[英]Simplest way to run an Expect script from Python
I'm trying to instruct my Python installation to execute an Expect script "myexpect.sh": 我正在尝试指示我的Python安装执行Expect脚本“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. 我在Windows上,所以将Expect脚本中的行重写为Python不是一种选择。 Any suggestions?
有什么建议? Is there anything that can run it the way "./myexpect.sh" does from a bash shell?
有没有什么可以像“./myexpect.sh”从bash shell那样运行它?
I have had some success with the subprocess command: 我在subprocess命令上取得了一些成功:
subprocess.call("myexpect.sh", shell=True)
I receive the error: 我收到错误:
myexpect.sh is not a valid Win32 application.
myexpect.sh不是有效的Win32应用程序。
How do I get around this? 我该如何解决这个问题?
Use the pexpect library . 使用pexpect库 。 This is the Python version for Expect functionality.
这是Expect功能的Python版本。
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. Pexpect有很多可以学习的例子。 For use of interact(), check out
script.py
from examples: 要使用interact(),请从示例中查看
script.py
:
(For Windows, there is an alternative to pexpect.) (对于Windows,有替代pexpect。)
Since it is an .expect script, I think you should change the extend name of your script. 由于它是.expect脚本,我认为您应该更改脚本的扩展名。
Instead of using 而不是使用
subprocess.call("myexpect.sh", shell=True)
you should use 你应该使用
subprocess.call("myexpect.expect", shell=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.