2
votes

I've been trying to read the output from a server with this code:

s = paramiko.SSHClient()
s.load_system_host_keys()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(hostname, port, username, password)
command = 'xe vm-list'
(stdin, stdout, stderr) = s.exec_command(command)

output = stdout.read()
x = output.replace("\n", ",").strip()
print(x)
s.close()

When the line "x = output.replace("\n", ",").strip()" is run "TypeError: a bytes-like object is required, not 'str'" is thrown.

What am I doing wrong?

2
output seems to be a string of bytes; you'll want to decode that to (character) string before applying replace - something like output.decode('utf-8').replace("\n", ",").strip(), adjusted to the specific encoding. - MrFuppes

2 Answers

1
votes

You have to decode bytes object to get string. To do this:

output = stdout.read().decode("UTF-8")

in there replace UTF-8 with the encoding of your remote machine.

0
votes

output is a bytes object, not str. You need to pass its replace method bytes as well, in this case by adding a b prefix to the literals:

x = output.replace(b"\n", b",").strip()