繁体   English   中英

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

[英]Running remote command in background using paramiko

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

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

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")))

Output:

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")))

Output:


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

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

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

提前致谢!

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

试试这个命令:

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

它相当于您的 Python 代码。 你会看到它也不会产生 output。 它甚至不会等待 15 秒,它会立即关闭。 与您的 Python 代码相同。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM