fun*_*ath 2 python windows ssh openssh paramiko
我的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")
Run Code Online (Sandbox Code Playgroud)
但是,我不清楚如何关闭/退出所有 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
Run Code Online (Sandbox Code Playgroud)
该代码基于使用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"
Run Code Online (Sandbox Code Playgroud)
所以我想知道是否是因为client.close()?如果我用 注释掉所有行会发生什么client.close()?这有帮助吗?这危险吗?当我退出本地 Python 脚本时,这是否会关闭我所有的 SSH 连接,因此不再需要client.close()?
而且我所有的机器都有 Windows 操作系统。
事实上,问题在于您关闭了 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()
Run Code Online (Sandbox Code Playgroud)
请注意,上述简单解决方案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)
Run Code Online (Sandbox Code Playgroud)
如果不需要分离 stdout 和 stderr,可以使用Channel.set_combine_stderr. 请参阅Paramiko ssh die/hang with big output。
关于你的问题SSHClient.close:如果你不调用它,当脚本完成时,当Python垃圾收集器清理挂起的对象时,连接将隐式关闭。这是一个不好的做法。即使Python不这样做,本地操作系统也会终止本地Python进程的所有连接。这也是一个不好的做法。无论如何,这都会终止远程进程。
| 归档时间: |
|
| 查看次数: |
8947 次 |
| 最近记录: |