【发布时间】:2021-05-17 08:20:25
【问题描述】:
我有一个SSH.py,目标是通过 SSH 连接到许多服务器以运行 Python 脚本 (worker.py)。我正在使用 Paramiko,但对它很陌生,并且在学习过程中不断学习。在我使用 ssh 连接的每台服务器上,我需要保持 Python 脚本运行——这是为了并行训练模型,因此脚本需要在所有机器上运行以共同更新模型参数/训练。服务器上的 Python 脚本需要运行,所以要么所有 SSH 连接都无法关闭,要么我必须想办法让服务器上的 Python 脚本在我关闭连接的情况下继续运行。
从广泛的谷歌搜索来看,您似乎可以使用 nohup 或:
client = paramiko.SSHClient()
client.connect(ip_address, username, password)
transport = client.get_transport()
channel = transport.open_session()
channel.exec_command("python worker.py > /logs/'command output' 2>&1")
但是,我不清楚我们如何关闭/退出所有 SSH 连接?我在cmd.exe 上运行SSH.py 文件,关闭cmd.exe 是否足以让所有进程远程关闭?
此外,我对client.close() 的使用是否符合我的目的?
请在下面查看我的代码。
# SSH.py
import paramiko
import argparse
import os
path = "path"
python_script = "worker.py"
# definitions for ssh connection and cluster
ip_list = ['XXX.XXX.XXX.XXX', XXX.XXX.XXX.XXX', XXX.XXX.XXX.XXX']
port_list = [':XXXX', ':XXXX', ':XXXX']
user_list = ['user', 'user', 'user']
password_list = ['pass', 'pass', 'pass']
node_list = list(map(lambda x: f'-node{x + 1} ', list(range(len(ip_list)))))
cluster = ' '.join([node + ip + port for node, ip, port in zip(node_list, ip_list, port_list)])
# run script on command line of local machine
os.system(f"cd {path} && python {python_script} {cluster} -type worker -index 0 -batch 64 > {path}/logs/'command output'/{ip_list[0]}.log 2>&1")
# loop for IP and password
for i, (ip, user, password) in enumerate(zip(ip_list[1:], user_list[1:], password_list[1:]), 1):
try:
print("Open session in: " + ip + "...")
client = paramiko.SSHClient()
client.connect(ip, user, password)
transport = client.get_transport()
channel = transport.open_session()
except paramiko.SSHException:
print("Connection Failed")
quit()
try:
channel.exec_command(f"cd {path} && python {python_script} {cluster} -type worker -index {i} -batch 64 > {path}/logs/'command output'/{ip_list[i]}.log 2>&1", timeout=30)
client.close() # here I am closing connection but above command should be running, my question is can I safely close cmd.exe on which I am running SSH.py?
except paramiko.SSHException:
print("Cannot run file. Continue with other IPs in list...")
client.close()
continue
代码基于Running process of remote SSH server in the background using Python Paramiko
编辑:好像 channel.exec_command() 没有执行命令
f"cd {path} && python {python_script} {cluster} -type worker -index {i} -batch 64 > {path}/logs/'command output'/{ip_list[i]}.log 2>&1"
所以不知道是不是因为client.close()?如果我用client.close() 注释掉所有行会怎样?这会有帮助吗?这很危险吗?当我退出本地 Python 脚本时,这会关闭我所有的 SSH 连接,因此不需要client.close()?
而且我所有的机器都有 Windows 操作系统。
【问题讨论】:
标签: python windows ssh paramiko openssh