Netmiko - backup-cisco.py.md

from pprint import pprint
from netmiko import ConnectHandler
from time import time
import json, os, threading, sys

def config_worker( ip, username, password, extra ):

    #---- Connect to the device ----
    print ("---- Connecting to device {0}".format( ip ))

    #---- Connect to the device
    session = ConnectHandler( device_type = "cisco_s300", ip = ip, username = username, password = password, global_delay_factor=2 )

    if extra == "extra":
        #---- Use CLI command to get configuration data from device
        print ("---- Retrieving result of extra command")
        config_data = session.send_command("show mac address-table",expect_string=r"#",delay_factor=6)

        #---- Write out configuration information to file
        print ("---- Storing extra command output: ", basepath + "extra/" + ip)
        with open( basepath + "extra/" + ip, "w" ) as config_out:  config_out.write( config_data )

    else:
        #---- Use CLI command to get configuration data from device
        print ("---- Retrieving configuration from device")
        config_data = session.send_command("show run",expect_string=r"#",delay_factor=6)

        #---- Use CLI command to save configuration on device
        session.send_command("wr",expect_string=r"Overwrite file",delay_factor=6)
        session.send_command("Y",expect_string=r"Copy succeeded",delay_factor=6)

        #---- Write out configuration information to file
        print ("---- Storing configuration: ", basepath + "configs/" + ip)
        with open( basepath + "configs/" + ip, "w" ) as config_out:  config_out.write( config_data )

    session.disconnect()

    return

#==============================================================================
# ---- Main: Get Configuration
#==============================================================================

#---- Define base path to run from anywhere
basepath = os.path.abspath(os.path.dirname(__file__)) + "/"

#---- Retrieve arguments if passed
if len(sys.argv) > 1:
    extra = sys.argv[1]
else:
    extra = None

#---- Retrieve creds from file
with open(basepath + "creds.json", "r") as f:
    creds = json.load(f)

username = creds["CISCO"]["USERNAME"]
password = creds["CISCO"]["PASSWORD"]

#---- Retrieve list of IPs from file
ips = [line.rstrip("\n") for line in open( basepath + "devices-cisco")]

starting_time = time()

config_threads_list = []

for ip in ips:
    print ("---- Creating thread for: ", ip)
    config_threads_list.append( threading.Thread( target=config_worker, args=( ip, username, password, extra, ) ) )

print ("---- Begin get config threading ----")
for config_thread in config_threads_list:
    config_thread.start()

for config_thread in config_threads_list:
    config_thread.join()

print ("---- End get config threading, elapsed time=", time() - starting_time)