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秒會去讀取一次標準輸出的內容

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章