我创建了一个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
我已通读 documentation on the python.org site ,但无济于事。有谁有一个巧妙的解决方案可以从 .py 代码中执行 bash 脚本吗?
解决方案:这段代码对我有用。
child = subprocess.Popen(['bash', '-c', './myscript.txt'], stdout = subprocess.PIPE)
使用此代码将 Expect 文件调用到 ssh 并从 .py 文件向服务器发送命令 - 如果您在计算机上构建 pycrypto/paramiko 时遇到问题,这是有用的解决方案。
最佳答案
这是您的期望脚本的 python 实现:
import paramiko
user = "user"
pass = "pass"
host = "host"
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, port=22, username=user, password=pass)
client.exec_command("./mycommand1")
client.exec_command("./mycommand2")
client.close()
关于python - 在 python 中执行 bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11147548/