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.


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_ ='unity_mem_util_%H_%M_%d_%m_%Y.log')
date_ ='%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',
    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

## 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):

fh = logging.FileHandler(logdir + logfile_)

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

# add the handlers to the logger
logger.addHandler(fh)'Network SNMP server config disable script started @ {}'.format(date_))

#Open the file having Unity arrays service account details
with open (src,'r') as lines:'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))' DC - {}  Switch Name - {} IP - {}'.format(dc, sw, ip))
        un = 'user'
        pw = 'Password'

        #Connecting to the switch
            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")
  'Switch version details :\n {}'.format(ver))
            print('Show version command executed:\n{}'.format(ver))
            #Change to config term 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)
  '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))
  '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))
  'Switch-Nexus history output :\n {}'.format(history2))

            #Exit from the switch

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




Leave a Reply

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

You are commenting using your 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