cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
376
Views
0
Helpful
3
Replies

TypeError: argument should be integer or bytes-like object, not 'str'

shawn-horne
Level 1
Level 1

I am trying to use a basic telnet script in python 3.9.11 to connect to a device in devnet sandbox.  The code is below:

import getpass
import sys
import telnetlib

HOST = "10.10.20.48"
user = input("Enter your telnet username: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("Username: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")

After entering my password I am getting the following error:

TypeError: argument should be integer or bytes-like object, not 'str'

 

3 Replies 3

Hey @shawn-horne this is a classic Python 2 versus 3 issue. This is because strings were handled as bytes by default in Python 2, but in Python 3, strings are Unicode. Per your errors these should be bytes, not strings.

Your fix is to you need to "encode" your string variables into bytes. Fix this and it will work fine.

On a side note, telnetlib is not longer supported after Python 3.11. Would suggest to move to Netmiko. 

Hope this helps.

 

Please mark this as helpful or solution accepted to help others
Connect with me https://bigevilbeard.github.io

I tried converting to a byte using the below updated code but still getting the same error which I have also placed below the code snippet.

import getpass
import sys
import telnetlib

HOST = "10.10.20.48"
user = input("Enter your telnet username: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)

tn.read_until("Username: ")
tn.write(user.encode('ascii') + b"\n")

if password:
tn.read_until("Password: ")
tn.write(password.encode('ascii') + b"\n")

Traceback (most recent call last):
File "/home/developer/pythonscript2.py", line 10, in <module>
tn.read_until("Username: ")
File "/usr/lib/python3.10/telnetlib.py", line 304, in read_until
i = self.cookedq.find(match)
TypeError: argument should be integer or bytes-like object, not 'str'

Arh I see your issue, you need to add a “b”prefix to the search strings inside the read_until methods. Then Python treats those strings as bytes constants.

Please mark this as helpful or solution accepted to help others
Connect with me https://bigevilbeard.github.io