python-3.xtelnetlib

How to include a variable in a string to a telnetlib write function


I have been trying to make a loop in the following script:

import getpass
import telnetlib

HOST = "192.168.122.188"
user = input("Enter your telnet username: ")
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"enable\n")

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

# Part to parse in a for loop
tn.write(b"int loop 0\n")
tn.write(b"ip address 1.1.1.1 255.255.255.255\n")
tn.write(b"int loop 1\n")
tn.write(b"ip address 2.2.2.2 255.255.255.255\n")

tn.write(b"router ospf 1\n")
tn.write(b"network 0.0.0.0 255.255.255.255 area 0\n")
tn.write(b"end\n")
tn.write(b"exit\n")

print(tn.read_all().decode('ascii'))

The script works, but I would like to use a for loop in this part:

tn.write(b"int loop 0\n")
tn.write(b"ip address 1.1.1.1 255.255.255.255\n")
tn.write(b"int loop 1\n")
tn.write(b"ip address 2.2.2.2 255.255.255.255\n")

I have tested contatenating and using str(),

for i in range(2):
    tn.write(b"int loop "+ str(i)+"\n")
    tn.write(b"ip address "+str(i)+'.'+str(i)+'.'+str(i)+'.'+str(i) + " 255.255.255.255\n")

and it gives an error after introducing a password

Traceback (most recent call last):
  File "R1_scr1.py", line 22, in <module>
    tn.write(b"int loop "+ str(i)+"\n")
TypeError: can't concat str to bytes

If I use a print() in place of tn.write() the loop writes in screen the strings but no if I use tn.write(). Probably I am missing something with this function.


Solution

  • Note that in your working code you're passing a string as bytes to the tn.write function (the 'b' before the quotes.

    tn.write(b"int loop 0\n")
    

    Now, if you try to do something like this:

    tn.write(b"int loop "+ str(i)+"\n")
    

    only the first part of the string is casted to bytes, the rest remains of type string.

    So all you need to do is to cast all of your strings to bytes before passing them to tn.write, eg like this:

    tn.write( str.encode("int loop " + str(i)+ "\n") )
    

    This is because the telnetlib was made for Python2, where the str type was a bytestring. Since Python3 the str type is unicode.