Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 telnetlib "bytes-like object is required"

Tags:

python

I am new to python and I would like to make a program that sends commands to a 2960 Cisco switch and have it display back the results.

I am able to make a connection to the switch and have it show me my banner message, but once I try to type my username and password, everything goes down hill. Here is the error message I get:

Traceback (most recent call last):
  File "C:/Users/jb335574/Desktop/PythonLearning/Telnet/TelnetTest2.py", line 8, in <module>
    tn.read_until("Username: ")
  File "C:\Users\admin1\AppData\Local\Programs\Python\Python35-32\lib\telnetlib.py", line 302, in read_until
    i = self.cookedq.find(match)
TypeError: a bytes-like object is required, not 'str'

Here is my code:

import telnetlib

un = "admin1"
pw = "password123"

tn = telnetlib.Telnet("172.16.1.206", "23")
tn.read_until("Username: ")
tn.write("admin1" + '\r\n')
tn.read_until("Password: ")
tn.write("password123" + '\r\n')
tn.write("show interface status" + '\r\n')

whathappened = tn.read_all()
print(whathappened)$
like image 232
StarThorn Avatar asked Jan 05 '23 00:01

StarThorn


1 Answers

The Python 3 telnetlib documentation is very explicit about wanting "byte strings". Regular Python 3 strings are multi-byte character strings without an explicit encoding attached; to make byte strings of them means either rendering them down, or generating them as pre-rendered bytestring literals.


To generate a byte string from a regular string, encode it:

'foo'.encode('utf-8') # using UTF-8; replace w/ the encoding expected by the remote device

or specify it as a bytestring literal if the encoding you're using for your source code is compatible with the encoding the remote device expects (insofar as the characters included in a constant string are concerned):

b'foo'

Thus:

tn.read_until(b"Username: ")
tn.write(b"password1\r\n")
tn.read_until(b"Password: ")

...etc.

like image 69
Charles Duffy Avatar answered Jan 17 '23 04:01

Charles Duffy