cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
85767
Views
35
Helpful
18
Replies

Basic Python Script

nemenciobeberu
Level 1
Level 1

Hi All,

 

im working as WAN edge engineer and still  telnet/ssh manually to device. I'm new and studying python to automate things but most of the videos i watched is using either mac or ubuntu as host pc. 

my office laptop is using windows and i cannot bring other pc inside our office. Can anyone help or maybe share simple python script hosted in windows box to access routers/switch and run show ip interface brief?

 

Thanks in advance 

Bebu

 

18 Replies 18

Joseph W. Doherty
Hall of Fame
Hall of Fame
Python 2.x or 3.x?

Hi Joseph,

 

Either Python 2.7 or 3.x though i want to focus later in 3.6 in continuous studies but for now i just want to study fundamentals and see sample working python script to telnet/ssh routers sourcing from Windows OS host .  then later play around there for continue and improvement.

 

 

 

I've been using 3.x, but there are, I believe, public libraries that will support telnet and/or SSH for 2.x. For 3.x and Windows, though, I came up dry searching for such.

So, what I did for 3.x and Windows, I run PuTTY's command line plink as a subprocess, and interact with it using std in/out pipes. The problem with this is, by default, Python's Windows are synchronous. However, they can be converted to asynchronous operation by making a call to Windows.

Personally, I would provide you a working Python 3.x script example (of the above), but my employer may consider it a proprietary work product.

That said, http://stackoverflow.com/questions/34504970 is critically important to accomplishing the above.

Hi Joseph,

 

Thanks for your input atleast i have some direction on how to proceed via Windows. also have you tried using secureCRT? there is an option in secureCRT (Menu bar-->Script-->Run) then it is accepting .py filename. Maybe this can be a good start also to create .py file and just load directly from secureCRT then no need to import telnetlib or same stuff

 

Sorry, no, I haven't tried SecureCRT's script run capability.

 

PS:

BTW, using plink.exe, you only need it, you don't need to import anything else, such as a telnet lib.

juan-ruiz
Level 1
Level 1

 

First I suggest you install the Paramiko ssh library and its name is Netmiko.

So if you have python installed with root or admin privileges execute the command  pip install netmiko.

Once installed take a look at this great link with a lot of good examples.

 

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

Let me know if this helps.

Also if you are looking to do this command across many devices that support SSH then from a script perspective I suggest you store all of your routers IP addresses on a text file and create your script with the following structure. 

 

Create your required netmiko variables 

create a variable to read a text file

Load the text file for reading 

execute a for loop against the text file 

Pass the IP of the router to the netmiko and required credentials.

Pass your commands and store output to a text file. This can be done from the command line with simple redirection or you can create another file object variable for writing and write to it. 

 

access each of the router IP address 

Let us know how far you get. 

 

HI Juan,
Paramiko and Netmiko is only available in linux/mac is it? My office host OS is Windows 10.
im using netmiko in ubuntu linux via docker and i can execute some basic scripts.

Almost all python libraries except some exotic are platform independent. You can run netmiko on Windows without any problems.

Seb Rupik
VIP Alumni
VIP Alumni

Hi there,

Here's a script, the result of 10 minutes work with some limited error checking:

#!/usr/bin/env python3
import getpass
import csv
import netmiko
import paramiko
from argparse import ArgumentParser


def main():
    parser = ArgumentParser(description='Arguments for running oneLiner.py')
    parser.add_argument('-c', '--csv', required=True, action='store', help='Location of CSV file')
    args = parser.parse_args()

    ssh_username = input("SSH username: ")
    ssh_password = getpass.getpass('SSH Password: ')

    with open(args.csv, "r") as file:
        reader = csv.DictReader(file)
        for device_row in reader:
            try:
                ssh_session = netmiko.ConnectHandler(device_type='cisco_ios', ip=device_row['device_ip'],
                                                     username=ssh_username, password=ssh_password)

                print("+++++ {0} +++++".format(device_row['device_ip']))
                ssh_session.send_command("terminal length 0")
                print(ssh_session.send_command("sh ip int br"))
                ssh_session.send_command("terminal length 30")
                ssh_session.disconnect()

            except (netmiko.ssh_exception.NetMikoTimeoutException,
                    netmiko.ssh_exception.NetMikoAuthenticationException,
                    paramiko.ssh_exception.SSHException) as s_error:
                print(s_error)


if __name__ == "__main__":
    main()

https://github.com/sebrupik/srupik-apic-em-tools/blob/master/frozenPony/src/oneLinerSimple.py

 

You will need a CSV file with the following format:

device_ip
1.1.1.1
1.1.1.2
1.1.1.3

The script will print to standard output so you should pipe the output for a local file.

 

If you are being forced to use a Windows PC, install a Linux VM on it. In my very limited testing on Windows I found that python ran very slowly, as soon as I started developing on a Linux VM performance was significantly better, not to mention more libraries being available.

 

cheers,

Seb.

Good suggestion about using a Linux VM under Windows.

I also recommend installing a Linux VM under Windows to work on development.

 

For any engineers out there looking to become network programmers...espcially looking to learn network related Python programming...........

 

I'd recommend you check out:

https://www.automate-the-network.com

 

You'll find a wealth of practical python code for network engineering, and a working VM/OVA to download, that's ready to go with an enterprise grade automation system, including individual scripts and instructional guide, and instructional videos,

 

All open source and free, released under the GPL/GNU project

 

This also includes the ability to automatically generate world class Visio diagrams, and automatically discover Cisco networks too...

Interesting/nice link.

HI, it's a nice script, so could you please give some clue for script for cisco with enable password

Hi there,

Good point. The script assumes the user account has privilege 15. If you need to specify an enable password, then pass it as the 'secret' parameter in the ConnectHandler:

enable_secret = "super_foo"

ssh_session = netmiko.ConnectHandler(device_type='cisco_ios', ip=device_row['device_ip'], 
username=ssh_username, password=ssh_password,
secret=enable_secret)

...then you need to move into enable mode once the connection has been established:

                ssh_session.enable()
                print("+++++ {0} +++++".format(device_row['device_ip']))
                ssh_session.send_command("terminal length 0")
                print(ssh_session.send_command("sh ip int br"))
                ssh_session.send_command("terminal length 30")
                ssh_session.disconnect()

cheers,

Seb.

Review Cisco Networking products for a $25 gift card