Cisco config backup via Telnet

From Daco.tech Technical Documentation

Usage:

Edit your credentials inside the script.

Provide a file called ip_list.txt, like so:

192.168.1.1
192.168.1.2
...


CAVEAT: Telnet is completely insecure and should never be used in a production environment.

I only use Telnet when connecting to a buggy GNS3 router, if the SSH connection isn't available.

I should add some proper exception handling for connection problems.

N.B. The original idea was from Mihai Catalin Teodosiu, at the GNS3 academy. I added some code to better fit my needs.

Code:

#!/usr/bin/env python
 
import telnetlib
import time
import re
 
def telnet_connection(ip):
    # Ask user for telnet credentials
    # username = raw_input('Enter your username: ')
    # password = raw_input('Enter your password: ')
    username = 'cisco'
    password = 'cisco'
 
    # Telnet port
    port = 23
 
    # Connection timeout in seconds for blocking operations, like the connection attempt
    connection_timeout = 5
 
    # Timeout in seconds. Read until string is found or until timeout
    reading_timeout = 5
    try:
        # Logging into device
        connection = telnetlib.Telnet(ip, port, connection_timeout)
 
        # Waiting to be asked for username
        router_output = connection.read_until('Username:', reading_timeout)
 
        # Enter username when asked and newline for 'enter'
        connection.write(username + '\n')
 
        # Waiting to be asked for password
        router_output = connection.read_until('Password:', reading_timeout)
 
        # Enter the password
        connection.write(password + '\n')
 
        time.sleep(1)
 
        # Test code: trying to extract the hostname from device:
        # Let's store the first line displayed after connection in a variable
        # This should be the command prompt from our device (e.g. Router1#)
 
        hostname = connection.read_very_eager()
 
        # Use a regex to extract only valid characters from the command prompt:
        # The returned string should contain only the valid characters from a Cisco router host name
        # We don't want to extract the last character, which could be a dash (Cisco command prompt #)
        # The following regex will extract only alphanumeric chars, hyphens and underscores, which can appear in a valid Cisco host name
        hostname = re.search('[a-zA-Z0-9_-]+', hostname)
        if hostname:
            hostname = hostname.group()
        print 'Saving config for', hostname
 
        # Setting terminal length to zero - no pagination
        connection.write('terminal length 0\n')
 
        time.sleep(1)
 
        # Send a 'show run' command to display the running config
        connection.write('show run\n')
        time.sleep(1)
 
        # Store this 'show run' in a variable
        router_output = connection.read_very_eager()
 
        # Write the 'show run' output into a new file, with hostname + .txt extension:
        with open(hostname + '.txt', 'w') as f:
            f.write(router_output)
 
        # close the connection
        connection.close()
 
    except IOError:
        print 'Input/output error'
 
 
 
def parse_ip_list():
    try:
        # Try to open our ip_list.txt
        with open('ip_list.txt', 'r') as f:
            # Check line by line
            for line in f:
                # rstrip method will try to remove all the newline characters, to produce a clean list
                # without this , the output of the file would contain many 'blank' lines
                line = line.rstrip()
                ip = line
                telnet_connection(ip)
 
    except IOError:
        print 'File error for ip_list.txt. Check file name and permissions.'
 
 
parse_ip_list()