运行 使用 paramiko 在后台执行远程命令

Running remote command in background using paramiko

当我尝试使用 paramiko 在后台 运行 远程命令时,我无法在标准输出中看到已执行命令的任何输出。请仔细阅读下图。

通常运行远程命令的脚本:

import paramiko
import select
import time
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('host_name', username='user_name', password='password')
COMMAND = "ls && sleep 15 && ls " #note here
stdin, stdout, stderr = client.exec_command(COMMAND, get_pty=True)

while not stdout.channel.exit_status_ready():
        time.sleep(1)
        if stdout.channel.recv_ready():
            rl, wl, xl = select.select([stdout.channel], [], [], 0.0)
            if len(rl) > 0:
                print("{}".format(stdout.channel.recv(1024).decode("utf-8")))
else:
    print("{}".format(stdout.channel.recv(1024).decode("utf-8")))

输出:

file1.txt
file2.txt
<waits for 15 seconds>
file1.txt
file2.txt

与 运行 后台远程命令相同的脚本:

import paramiko
import select
import time
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('host_name', username='user_name', password='password')
COMMAND = "ls && sleep 15 && ls &" # here is the change
stdin, stdout, stderr = client.exec_command(COMMAND, get_pty=True)

while not stdout.channel.exit_status_ready():
        time.sleep(1)
        if stdout.channel.recv_ready():
            rl, wl, xl = select.select([stdout.channel], [], [], 0.0)
            if len(rl) > 0:
                print("{}".format(stdout.channel.recv(1024).decode("utf-8")))
else:
    print("{}".format(stdout.channel.recv(1024).decode("utf-8")))

输出:


如您所见,控制台上打印了一个空行,程序在 one/two 秒后退出。我怀疑它是否真的在后台执行sleep 15并在启动后退出。

如果运行在后台调用远程命令,我需要做些什么吗?

我是 paramiko 模块的新手。也许你会觉得这个问题很简单。请分享您的意见。对像我这样的初学者会有很大的帮助。

提前致谢!

如果在后台执行命令,会话会立即结束,不会等待命令完成。

试试这个命令:

ssh -t user_name@host_name "ls && sleep 15 && ls &"

它等同于您的 Python 代码。你会看到它也没有产生任何输出。它甚至不会等待 15 秒,它会立即关闭。与您的 Python 代码相同。

$ ssh -t user_name@host_name "ls && sleep 15 && ls &"
Connection to host_name closed.
$

无论如何,如果您然后等待命令完成,我看不出在后台执行命令有什么意义。