This python script reads the device information from a csv file and fetches its configuration via telnet session and save to specified location.

CSV Template:

deviceIp,userName,password 
192.168.1.1,admin,secretpwd 
192.168.1.2,admin,secretpwd2

The script initiates telnet session with the device along with userId and password to login into enable mode and executes “show run” command to fetch the configuration


Python code to fetch switch configuration:

import telnetlib as tel
import csv
import datetime
import os


#Declaration
#path of the csv file
#deviceFilePath = "D:/Script/DeviceIp.csv"
#path to save the backup files
#directoryLocation = "D:/Script/"


#Methods
###This method initiate telnet connection to devices
def Initiate_Telnet(indexCount, hostIP, userId, passwd, directoryLocation):
    commands_ShowConfig = "sh run"
    commands_terminalLength = "terminal length 0"
    response = os.system("ping -n 1 -w 700 " + hostIP)
    if response == 0:
        try:
            #connecting to host device
            telConnection = tel.Telnet(hostIP, timeout=2)

            #sending username value and password value
            uName = telConnection.read_until('Username:'.encode('utf-8'), timeout=5)
            telConnection.write(userId.encode('utf-8') + b"\n")
            uPass = telConnection.read_until('Password:'.encode('utf-8'), timeout=5)
            telConnection.write(passwd.encode('utf-8') + b"\n")

            #checking for "#"
            telConnection.write(b"\n")
            mode = telConnection.read_until('#'.encode('utf-8'), timeout=5)
            #x = b' \r\nBZPDAMG0204#'
            mode = str(mode.decode('utf-8'))

            if(mode[-1] == "#"):
                #sending terminal length command to get full configuration
                telConnection.write(commands_terminalLength.encode('utf-8') + b"\n")
                telConnection.write(commands_ShowConfig.encode('utf-8') + b"\n")
            elif(mode[-1] == ":"):
                outputData = b"Password Wrong"
            elif(mode[-1] == ">"):
                outputData = b"Not Enable Mode"


            #sending terminal length command to get full configuration
            #telConnection.write(commands_terminalLength.encode('utf-8') + b"\n")
            #telConnection.write(commands_ShowConfig.encode('utf-8') + b"\n")

            #read till end, so passing a string which may not appear in the configuration
            outputData = telConnection.read_until('stringNotInConfiguration'.encode('utf-8'), timeout=5)

            #close telnet connection
            telConnection.close()
        except:
            outputData = b"telnet not available"
    else:
        outputData = b"Host not pinging"

    #exporting the data to text file and close file
    Write_Info_toFile(directoryLocation, hostIP, outputData)

    return (indexCount, hostIP)
#end Initiate_Telnet


###This method writes info to file
def Write_Info_toFile(directory, fileName, dataString):
    datestring = datetime.datetime.now()
    datestring = str(datestring).replace(':','_').replace('-','_').replace(' ','__').split('.')[0]
    
    #exporting the data to text file and close file
    dataString = dataString.decode('utf-8')
    
    #validation
    if(dataString == "telnet not available"):
        text_file = open(directory + "Log_backup_.txt", "a+")
        dataString = fileName + " " + dataString + "\n"
    elif(dataString == "Host not pinging"):
        text_file = open(directory + "Log_backup_.txt", "a+")
        dataString = fileName + " " + dataString + "\n"
    elif(dataString == ""):
        text_file = open(directory + "Log_backup_.txt", "a+")
        dataString = fileName + " Login Failed" + "\n"
    else:
        text_file = open(directory + fileName + "_backup_" + datestring + ".txt", "w")

    text_file.write(dataString)
    text_file.close()
#end Write_Info_toFile

#start function
def Start_Telnet(deviceFilePath = "D:/Script/DeviceIp.csv", directoryLocation = "D:/Script/"):
    with open(deviceFilePath) as csvDeviceDetails:
        csdData = csv.reader(csvDeviceDetails, delimiter=',')
        #print(csdData)
        lineCount = 0
        for (ipAddress, userName, password) in csdData:
            if(lineCount == 0):
                #First entry is heading
                lineCount += 1
            else:
                lineCount += 1
                Initiate_Telnet(0, ipAddress, userName, password, directoryLocation)

Start_Telnet("D:/Script/DeviceIp.csv", "D:/Script/")

Note: This works for switches which has login to “enable mode”, for other modes, extra conditions has to be added.

Hope you liked this article and thank you for reading