Loren Zimmer
Loren Zimmer

Reputation: 480

Python3 .replace yielding TypeError: a bytes-like object is required, not 'str'

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?

Upvotes: 2

Views: 2541

Answers (2)

obayhan
obayhan

Reputation: 1732

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.

Upvotes: 2

ShadowRanger
ShadowRanger

Reputation: 155497

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()

Upvotes: 0

Related Questions