【问题标题】:Running remote command in background using paramiko使用 paramiko 在后台运行远程命令
【发布时间】:2020-07-24 22:06:51
【问题描述】:

当我尝试使用 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")))

输出:


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

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

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

提前致谢!

【问题讨论】:

  • 嗯,除了以COMMAND 开头的一行注释之外,这两个脚本是相同的。
  • 对不起,我在第二种情况下错过了COMMAND 末尾的&amp;。现在添加。谢谢你指出来。
  • 作为我的应用程序要求的一部分,我必须在后台运行它,您可以看到,我正在等待它完成。对于您的第二个问题,是的,它是 ubuntu 16.04。

标签: python python-3.x ssh command-line paramiko


【解决方案1】:

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

试试这个命令:

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.
$

无论如何,如果您等待命令完成,我看不到在后台执行命令的意义。

【讨论】:

  • 谢谢。是的,我知道我们可以执行并等待其完成。但我确实在后台启动了Command A,并开始在同一个 ssh 会话中执行其他操作,这可以在执行该Command A 后完成。注意:Command A 需要很长时间。
  • 因此,在同一个 SSH 连接上使用两个 exec_command 调用运行 A 和 B。这就是使用代码的方法。 – 在后台运行命令是一种交互式 shell 功能,供交互式人类使用。不是为了代码。 ——而且你的代码并没有做你想做的事。您等待 A 完成。你永远不会执行 B(在 A 运行时)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多