• paramiko远程持续获取内容


    在使用paramiko时,我们在用exec_command(command) 时更多的是一起读回数据,但实际官方还有更详细的说明。

    当前遇到的需求就是,当执行某个命令时,有进度条的输出,我们需要持续获取进度条输出,而不是执行完成后再输出进度条。

    再看看官网的说明:

    exec_command(command)
    Execute a command on the server. If the server allows it, the channel will then be directly connected to the stdin, stdout, and stderr of the command being executed.
    
    When the command finishes executing, the channel will be closed and can’t be reused. You must open a new channel if you wish to execute another command.
    
    Parameters:	command (str) – a shell command to execute.
    Raises:	SSHException – if the request was rejected or the channel was closed
    

      这是执行。

    我们再看看返回的说明:

    recv(nbytes)
    Receive data from the channel. The return value is a string representing the data received. The maximum amount of data to be received at once is specified by nbytes. If a string of length zero is returned, the channel stream has closed.
    
    Parameters:    nbytes (int) – maximum number of bytes to read.
    Returns:    received data, as a str/bytes.
    Raises:    socket.timeout – if no data is ready before the timeout set by settimeout.

    解释一下,也就是当默认时,recv会一次获取所有的内容。

    那么也就是我们可以通过这个方式获取进度条的实时输出

    简单的代码如下:

    _, stdout, stderr = self.ssh.exec_command(cmd, get_pty=True)
    while True:
            v = stdout.channel.recv(1024)
            if not v:
                break
            print(str(v))
            time.sleep(3)

    每隔3秒会去读取一次标准输出的内容

    Email:362299908@qq.com
  • 相关阅读:
    树的遍历
    动态规划之背包问题
    Dijkstra算法
    最短路径
    关于数学公式Markdown
    子集数
    O、Θ、Ω
    AT212 P-CASカードと高橋君
    vector的使用方法
    P3512 [POI2010]PIL-Pilots 单调队列的应用
  • 原文地址:https://www.cnblogs.com/landhu/p/15222967.html
Copyright © 2020-2023  润新知