Python Forum
for loop script over telnet in Python 3.5 is not working - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: for loop script over telnet in Python 3.5 is not working (/thread-26695.html)



for loop script over telnet in Python 3.5 is not working - abhijithd123 - May-10-2020

Hi,



I am getting below error while running For loop script over telnet.

Error:
Traceback (most recent call last): File "telnetgta.py", line 22, in <module> tn.write(b"int loopback " + str(n) + "\n") TypeError: can't concat bytes to str
I am using Python 3.5.2 in ubuntu docker.

root@Automation_Server:~# python3.5

Python 3.5.2 (default, Apr 16 2020, 17:47:17)

[GCC 5.4.0 20160609] on linux

Type "help", "copyright", "credits" or "license" for more information.



The script is shown below,

import sys

import getpass

import telnetlib



HOST = "192.168.122.150"

user = input("Enter your remote account: ")

password = getpass.getpass()



tn = telnetlib.Telnet(HOST)



tn.read_until(b"Username: ")

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

if password:

    tn.read_until(b"Password: ")

    tn.write(password.encode('ascii') + b"\n")



tn.write(b"conf t\n")



for n in range (2):
    tn.write(b"int loopback " + str(n)  + "\n")



tn.write(b" exit\n")

tn.write(b"exit\n")

print(tn.read_all().decode('ascii'))
My goal is to write int loopback 0,1 on cisco device.


RE: for loop script over telnet in Python 3.5 is not working - bowlofred - May-10-2020

Quote:tn.write(b"int loopback " + str(n) + "\n")

The expression you have in the argument is a bytestring, a str, and a str, all added together. But you can't add bytestrings and strs.

>>> b"foo" + "foo"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't concat str to bytes
If whatever you need to feed bytes to needs UTF-8, then you should generally encode your str to turn it into bytes.

>>> b"foo" + "foo".encode()
b'foofoo'