cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
10128
Views
7
Helpful
0
Comments
Samer R. Saleem
Level 4
Level 4

In this post, I'm going to use Python and Telnet Library to login into a list of IP addresses and execute some commands and send the output to separated text files.

My network contains different vendor access switches and I need to collect some information like product number or serials from each IP in the file called (Ciscoswitch.txt).

Note: I don't recommend using Telnet, using secure version to connect to network devices like SSH is of course the best option.

but I'm going to use this as beginner guide to collect information from a list of IP addresses which will represent switches or routers and then save the output of the code to a text file per IP address.

 

 

As usual, we start by importing the telnet library into python:

#!/usr/bin/env python
import getpass
import telnetlib

user = ("Admin")
password = ("password")

f = open ("C:\\Users\\user.name\\Desktop\\python\\Ciscoswitch.txt")

 

for line in f:
    print "Getting Serials from Device  " + (line)
    HOST = line.strip()
    tn = telnetlib.Telnet(HOST)

    tn.read_until("Username:")
    tn.write(user + "\n")
    if password:
        tn.read_until("Password:")
        tn.write(password + "\n")

 

#this section is the switch configuration part
    tn.write("enable \n")
    tn.write("password\n")


    tn.write("show version | section  WS-C2960S-48LPS-L\n")

tn.write("exit\n")
#tn.write("exit\n")
    readoutput = tn.read_all()

saveoutput = open("C:\\Users\\user.name\\Desktop\\serials\\switch" + HOST + ".txt", "w")

saveoutput.write(readoutput)
    saveoutput.write("\n")
    saveoutput.close

print tn.read_all()

===================================================================

 

Same code can be used for checking interfaces or uplinks status.

As you can see that I have added username and password directly to the code, but you can change this by adding a line where you will get request to input username and password manually.

Note, if you are facing problem with executing the code due to speed, then you can add sleep time to the code to slowdown the code a little bit.

 

So as you can see, the most important lines in the code are the path where python will check the IP addresses in order to start checking line by line bases, and the second line is where python will save the output of the command "Show version" into a file with the name of the file set as the IP address.

I hope this was useful!

 

Samer R. Saleem

Getting Started

Find answers to your questions by entering keywords or phrases in the Search bar above. New here? Use these resources to familiarize yourself with the community:

Review Cisco Networking for a $25 gift card