pythonpython-3.xsshparamikopty

Running command with paramiko PTY gives error: write() argument must be str, not bytes


I'm using paramiko to connect to the remote machine via SSH where a bash command is ran and the stdout output needs to be read line by line as they are sent.

This is what I have so far. get_pty=True needs to be set.

import paramiko
import sys

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect('my.host.com', 22, 'root', key_filename="/home/me/.ssh/id_ed25519")

stdin, stdout, stderr = ssh.exec_command("ls", get_pty=True)
while True:
    v = stdout.channel.recv(1024)
    if not v:
        break
    sys.stdout.write(v)
    sys.stdout.flush()

Running this gives the error

  File "/home/me/test.py", line 13, in <module>
    sys.stdout.write(v)
TypeError: write() argument must be str, not bytes

What is the correct way to read the multi-line output from running the command?


Solution

  • The channel stdout gave you bytes, but the sys.stdout is a TextIO. Use sys.stdout.buffer.write(...) instead.