我有一个python脚本,它应该通过ssh连接到客户机并从客户机执行bash。作为一个测试场景,我只使用一台机器来连接,但目标是连接到多个客户机并从这些机器执行bash脚本。
我的Python代码:import os
import subprocess
import time
def ssh_login_execute():
if device['PWD'] != "":
run=('sshpass -p %s ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -t -p %s %s@%s' % (device['PWD'], device['PORT'], device['USER'], device['IP']))
else:
run=('ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -t -p %s %s@%s' % (device['PORT'], device['USER'], device['IP']))
cmd = ('cd %s' % (script_path))
run2=run.split()
run2.append(cmd)
t=subprocess.Popen(run2, stdout=subprocess.PIPE, stderr=open(os.devnull, 'w'))
print "I am in 192.168.1.97"
execute_tg()
return t
def execute_tg():
path = "/home/"
os.chdir(path)
print os.getcwd()
cmd=("sh my_script.sh")
t=subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
if __name__ == "__main__":
device = {}
device['PORT']=22
device['PWD']= "abcd"
device['USER']= "root"
device['IP']= "192.168.1.97"
script_path= "/home/"
ssh_login_execute()
在运行代码“python script.py”时,我将输出如下:I am in 192.168.1.97
/home/
Output is sh: 0: Can't open my_script.sh
尽管“my_script.sh”在192.168.1.97的/home目录中。
如何解决这个问题,同时使它可以扩展到ssh到多个客户机并执行bash。