12-30-2025 07:27 AM
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'
12-30-2025 08:24 AM
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.
12-30-2025 05:09 PM
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'
12-31-2025 12:34 AM
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.
Discover and save your favorite ideas. Come back to expert answers, step-by-step guides, recent topics, and more.
New here? Get started with these tips. How to use Community New member guide