Telnet Python Automation on Cisco Routers and Switches

Python Automation on Cisco Router and Switches

Today in this article we will see how a python script automatically logs into a Cisco Router using telnet and configure a loopback interface.

Here is the working Python script:


import getpass
import telnetlib

HOST = "192.168.1.205"
user = input("Enter your Username: ")
password = getpass.getpass()
enablepassword = 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.read_until(b"R1>")
tn.write(b"enable\n")
tn.write(enablepassword.encode('ascii') + b"\n")
tn.write(b"conf t\n")
tn.write(b"int loop 0\n")
tn.write(b"ip add 192.168.2.205 255.255.255.0\n")
tn.write(b"no sh\n")
tn.write(b"end\n")
tn.read_until(b"R1#")
tn.write(b"sh ip int brie\n")
tn.write(b"exit\n")
print(tn.read_all().decode('ascii'))


 

We are basically telling Python to:
  • Telnet on 192.168.1.205
  • Prompt for Username
  • Prompt to type login password and also ensure that the typed characters are not displayed on the screen as we have used getpass module.
  • As soon as we se R1> on the screen, we will execute “enable” command  which should prompt to enter enable password.
  • The python script then executes “conf t”  and goes to global configuration mode
  • Then it executes “int loop 0
  • Then it executes “ip add 192.168.2.205 255.255.255.0
  • Then it executes “no sh
  • Then it executes “end
  • Then it executes “sh ip int brie
  • Then it exits
  • Then it prints the output.

 

Here is the output of the Python script execution:


PS C:\Users\Administrator\Desktop> python .\Telnet.py
Enter your Username: cisco
Password:
Password:
conf t
Enter configuration commands, one per line.  End with CNTL/Z.
R1(config)#int loop 0
R1(config-if)#ip add 192.168.2.205 255.255.255.0
R1(config-if)#no sh
R1(config-if)#end
R1#sh ip int brie
Interface                  IP-Address      OK? Method Status                Protocol
Ethernet0/0                192.168.1.205   YES manual up                    up
Ethernet0/1                unassigned      YES unset  administratively down down
Ethernet0/2                unassigned      YES unset  administratively down down
Ethernet0/3                unassigned      YES unset  administratively down down
Loopback0                  192.168.2.205   YES manual up                    up
R1#exit

PS C:\Users\Administrator\Desktop>


 

HTH.

You may also like...

2 Responses

  1. Yoav says:

    Thank you for sharing

  2. Jon Jones says:

    This is a rather blunt way to do it. A more robust (But harder to setup way) is to use something like Expect.

Leave a Reply

Your email address will not be published. Required fields are marked *