Automate Cisco switches config using NETMIKO

Netmiko is a simplified module to manage Network devices via SSH. This module is developed by Kirk Byers. I would recommend all network engineers to learn and equip this module to automate day to day configuration tasks.

netmiko_show_arp

I’ve written a demo script to disable SNMP Server’s “globalenforcepriv” on both Cisco IOS and Nexus switches. Using this script we could make the necessary changes on 100’s of switches in few minutes saving time and energies of network engineers.

Al Sweigart wrote a book called ‘Automate boring stuff using python’. This is one of the scripts which could help network engineers to automate monotonous tasks using Python and Netmiko module.

Script will:

  • Take input file having IP addresses
  • Execute following commands in the configuration terminal
    • show version  [Show switch information]
    • no snmp-server globalenforcepriv [Disable globalenforcepriv]
    • copy running-config startup-config [Save changes to start-up config]
    • show history [Show executed commands]
  • This script is for demo purpose only hence the credentials are hard-coded in the script. Please use the usual method to securely pass the credentials as parameters to the script.
'''
This is Python script to disable snmpserver globalenforcepriv on network switches
'''


from netmiko import ConnectHandler # connect to cisco switches and execute cmds
import subprocess #Module to run commands on local or remote systems
from datetime import datetime # Date and time module
import os # Native OS operations and management
import emails # Geenrate email using SMTP
import time # Get time from system
import logging # Default Python logging module
import shutil # shell util used here to move files
import argparse # Pass arguments

#create a log file with system date and time stamp
logfile_ = datetime.now().strftime('unity_mem_util_%H_%M_%d_%m_%Y.log')
date_ = datetime.now().strftime('%H_%M_%d_%m_%Y')

def check_arg(args=None):

    parser = argparse.ArgumentParser(description='Script to disable Network SW \
                                     SNMPSERVER globalenforcepriv setting')

    parser.add_argument('-s', '--source',
                        help='Source filename required',
                        required='True')
    results = parser.parse_args(args)

    return (results.source)

src = check_arg()

logger = logging.getLogger('NW_SNMP_GLOBALENFORCEPRIV')
#set logging level
#logging.basicConfig(level=logging.INFO) # Python 2.x syntax
#toggle between DEBUG and INFO to see the difference
logger.setLevel(logging.DEBUG)
#logger.setLevel(logging.INFO)

## create file handler which logs even debug messages

#Create 'logs' folder if not exists. Change the path of logdir as your git folder

logdir = "logs/"
if not os.path.exists(logdir):
    os.makedirs(logdir)

fh = logging.FileHandler(logdir + logfile_)
fh.setLevel(logging.DEBUG)

# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s | %(name)s | %(levelname)s | %(message)s')
fh.setFormatter(formatter)

# add the handlers to the logger
logger.addHandler(fh)

logger.info('Network SNMP server config disable script started @ {}'.format(date_))

#Open the file having Unity arrays service account details
with open (src,'r') as lines:
    logger.info('Read source file with device details')
    lines = list(lines) # convert file object to list object
    del(lines[0]) # skip the header row
    for line in lines:
        value = line.split(',')
        dc = value[0] # dc
        sw = value[1] # switch name
        ip = value[2] # ip
        print ('Switch DC: {}'.format(dc))
        print ('Switch Name: {}'.format(sw))
        print ('Switch IP: {}'.format(ip))
        logger.info(' DC - {}  Switch Name - {} IP - {}'.format(dc, sw, ip))
        un = 'user'
        pw = 'Password'

        #Connecting to the switch
        try:
            net_connect = ConnectHandler(device_type='cisco_ios', ip=ip, username=un, password=pw)
            #show version of the switch
            ver = net_connect.send_command("show version")
            logger.info('Switch version details :\n {}'.format(ver))
            print('Show version command executed:\n{}'.format(ver))
            #Change to config term mode
            net_connect.config_mode()
            #Configuration config_commands
            config_commands = ['no snmp-server globalenforcepriv', 'end',
                               'copy running-config startup-config']
            #Run config commands
            config = net_connect.send_config_set(config_commands)
            logger.info('Switch Configuration Output :\n {}'.format(config))
            print('Config commands executed successfully:\n{}'.format(config))

            #Show history of commands for IOS
            history1 = net_connect.send_command("show history")
            print('Show history for IOS command executed successfully: \n {}'.format(history1))
            logger.info('Switch-IOS history output :\n {}'.format(history1))


            ##Show history of commands for Nexus
            history2 = net_connect.send_command("show cli history")
            print('Show history for nexus command executed successfully: \n {}'.format(history2))
            logger.info('Switch-Nexus history output :\n {}'.format(history2))

            #Exit from the switch
            net_connect.disconnect()

        except Exception as e:
            print('Error Occured while connecting to switch - {}  IP - {}: \n {}'.format(sw, ip, e))
            logger.info('Unable to connect to the switch - {} IP - {} :\n {}'.format(sw, ip, e))

 

References:

https://pynet.twb-tech.com/blog/automation/netmiko.html

https://pypi.org/project/netmiko/

https://github.com/ktbyers/netmiko

 

Advertisements

Written by Vinay

Proud and Tolerant Indian

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s