【发布时间】: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末尾的&。现在添加。谢谢你指出来。 -
作为我的应用程序要求的一部分,我必须在后台运行它,您可以看到,我正在等待它完成。对于您的第二个问题,是的,它是 ubuntu 16.04。
标签: python python-3.x ssh command-line paramiko