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 = ""
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.write(enablepassword.encode('ascii') + b"\n")
tn.write(b"conf t\n")
tn.write(b"int loop 0\n")
tn.write(b"ip add\n")
tn.write(b"no sh\n")
tn.write(b"sh ip int brie\n")


We are basically telling Python to:
  • Telnet on
  • 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
  • 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 .\
Enter your Username: cisco
conf t
Enter configuration commands, one per line.  End with CNTL/Z.
R1(config)#int loop 0
R1(config-if)#ip add
R1(config-if)#no sh
R1#sh ip int brie
Interface                  IP-Address      OK? Method Status                Protocol
Ethernet0/0         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           YES manual up                    up

PS C:\Users\Administrator\Desktop>



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 *