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.