我有一个 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。