我创建了一个 Expect 脚本,执行时,它会通过 ssh 连接到服务器并执行一系列命令。伪代码如下所示:
#!/usr/bin/expect
spawn ssh usr@myip
expect "password:"
send "mypassword\n";
send "./mycommand1\r"
send "./mycommand2\r"
interact
当从 bash shell ($ ./myscript.txt) 执行时,代码执行良好。我现在想做的是在 python 文件中添加一行,以与 bash shell 相同的方式运行脚本中的命令。伪代码如下所示:
import subprocess
def runmyscript():
subprocess.call("myscript.txt", executable="expect", shell=True)
def main():
run = runmyscript():
if __name__ == '__main__': main()
我已将 myscript.txt 脚本文件放在与 runmyscript.py 文件相同的目录中,但是当我运行 python 文件时,我收到错误:
WindowsError: [Error 2] The system cannot find the file specified
我已经读过python.org 网站上的文档 http://docs.python.org/library/subprocess.html,但无济于事。有谁有一个巧妙的解决方案可以从 .py 代码中执行 bash 脚本吗?
解决方案:这段代码对我有用。
child = subprocess.Popen(['bash', '-c', './myscript.txt'], stdout = subprocess.PIPE)
使用此代码调用 Expect 文件进行 ssh 并从 .py 文件向服务器发送命令 - 如果您在计算机上构建 pycrypto/paramiko 时遇到问题,这是有用的解决方案。