使用 Python Paramiko 在不同的 SSH 服务器中并行运行多个命令

问题描述 投票:0回答:1

我有一个

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 连接?我正在

SSH.py
上运行
cmd.exe
文件,关闭
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

代码基于使用Python Paramiko在后台运行远程SSH服务器的过程

编辑:看起来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
1个回答
6
投票

确实,问题在于您关闭了 SSH 连接。由于远程进程未与终端分离,因此关闭终端会终止该进程。在 Linux 服务器上,您可以使用

nohup
。我不知道什么是(如果有)Windows 等效项。

不管怎样,好像不需要关闭连接。我明白,您可以等待所有命令完成。

stdouts = []
clients = []

# Start the commands
commands = zip(ip_list[1:], user_list[1:], password_list[1:])
for i, (ip, user, password) in enumerate(commands, 1):
    print("Open session in: " + ip + "...")
    client = paramiko.SSHClient()
    client.connect(ip, user, password)
    command = \
        f"cd {path} && " + \
        f"python {python_script} {cluster} -type worker -index {i} -batch 64 " + \
        f"> {path}/logs/'command output'/{ip_list[i]}.log 2>&1"
    stdin, stdout, stderr = client.exec_command(command)
    clients.append(client)
    stdouts.append(stdout)

# Wait for commands to complete
for i in range(len(stdouts)):
    stdouts[i].read()
    clients[i].close()

请注意,上述使用

stdout.read()
的简单解决方案仅在您将命令输出重定向到远程文件时才起作用。如果你不这样做,命令可能会死锁

如果没有这个(或者如果您想在本地查看命令输出),您将需要这样的代码:

while any(x is not None for x in stdouts):
    for i in range(len(stdouts)):
        stdout = stdouts[i]
        if stdout is not None:
            channel = stdout.channel
            # To prevent losing output at the end, first test for exit,
            # then for output
            exited = channel.exit_status_ready()
            while channel.recv_ready():
                s = channel.recv(1024).decode('utf8')
                print(f"#{i} stdout: {s}")
            while channel.recv_stderr_ready():
                s = channel.recv_stderr(1024).decode('utf8')
                print(f"#{i} stderr: {s}")
            if exited:
                print(f"#{i} done")
                clients[i].close()
                stdouts[i] = None
    time.sleep(0.1)

如果不需要分离stdout和stderr,可以使用

Channel.set_combine_stderr
大大简化代码。请参阅 Paramiko ssh 因大输出而死亡/挂起


关于你关于

SSHClient.close
的问题:如果你不调用它,当脚本完成时,当Python垃圾收集器清理挂起的对象时,连接将隐式关闭。这是一个不好的做法。即使Python不这样做,本地操作系统也会终止本地Python进程的所有连接。这也是一个不好的做法。无论如何,这都会终止远程进程。

© www.soinside.com 2019 - 2024. All rights reserved.