简体   繁体   English

在读取所有输出之前,Paramiko完成处理

[英]Paramiko finish process before reading all output

I'm Trying to make a real time SSH Library, but as usually getting stuck on things, I have taken this code from Long-running ssh commands in python paramiko module (and how to end them) . 我正在尝试制作一个实时SSH库,但通常会遇到一些麻烦,我从python paramiko模块中的ssh命令中使用了这段代码(以及如何结束它们) But this code doesn't prints the whole output. 但是此代码不会显示整个输出。

I guess that when the while loop exits on channel.exit_status_ready() the channel still have data to read. 我猜想,当while循环在channel.exit_status_ready()上退出时,该通道仍然有要读取的数据。 I've been trying to fix this but the fix was not on all inputs. 我一直在尝试解决此问题,但并非所有输入均已解决。

How can I make this work to print all kind of commands? 如何使这项工作能够打印所有类型的命令?

import paramiko
import select

client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('host.example.com')
channel = client.get_transport().open_session()
channel.exec_command("cd / && ./test.sh")
while True:
    if channel.exit_status_ready():
        break
    rl, wl, xl = select.select([channel], [], [], 0.0)
    if len(rl) > 0:
        print channel.recv(1024)

test.sh: test.sh:

echo 1
wait 1
echo 2
wait 1
echo 3

Output: 输出:

1

2

Process finished with exit code 0

Thanks. 谢谢。

I couldn't reproduce problem with your command, but I can reproduce it with command like cat some_big_file.txt . 我无法重现您的命令问题,但可以使用cat some_big_file.txt类的命令重现问题。

So looks like you are right in your hypothesis. 因此,看起来您的假设正确。 Exit status can be ready before you read all the stuff from your channel . 在您从channel读取所有内容之前,可以准备退出状态。 It's not clear if you really need to use select . 还不清楚您是否真的需要使用select If not I would rewrite loop: 如果没有,我会重写循环:

while True:
    buf = channel.recv(1024)
    if not buf:
        break
    print buf

Such loop will keep reading the channel while it has some data in it. 这样的循环将在其中包含一些数据的同时继续读取该通道。 If you really want to use select you can put the above loop just after your loop. 如果您确实要使用select ,则可以将上述循环放在循环之后。 It will read and print remaining data. 它将读取并打印剩余数据。

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

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