Python Forum
for loop script over telnet in Python 3.5 is not working
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
for loop script over telnet in Python 3.5 is not working
#1
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.
Reply
#2
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'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Button to stop while loop from another script Absolutewind 5 818 Sep-25-2023, 11:20 PM
Last Post: deanhystad
  Is there a *.bat DOS batch script to *.py Python Script converter? pstein 3 3,000 Jun-29-2023, 11:57 AM
Last Post: gologica
  while loop not working-I am using sublime text editor mma_python 4 1,060 Feb-05-2023, 06:26 PM
Last Post: deanhystad
  [SOLVED] [Linux] Script in cron stops after first run in loop Winfried 2 894 Nov-16-2022, 07:58 PM
Last Post: Winfried
  WHILE Loop - constant variables NOT working with user input boundaries C0D3R 4 1,434 Apr-05-2022, 06:18 AM
Last Post: C0D3R
  how to loop a script? ZYSIA 1 1,966 Jul-22-2021, 06:46 AM
Last Post: Gribouillis
  Telnet command in Python 3.9 Dre83 0 1,928 Nov-11-2020, 11:42 AM
Last Post: Dre83
  Why is the while loop not working? mcoliver88 5 3,044 Aug-18-2020, 03:27 PM
Last Post: deanhystad
  Infinite loop not working pmp2 2 1,607 Aug-18-2020, 12:27 PM
Last Post: deanhystad
  Loop not working Nonameface 8 2,832 Jul-19-2020, 12:27 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020