Python Script that SSH to a switch and execute commands for ‘x’ times

Below is a sample python code that can login to a switch via SSH and gather few command outputs and display it on console. SSH sessions are repeated for ‘x’ number of times.

Paramiko SSH module is used in this script. Paramiko is a native Python implementation of SSH. This module can be installed on a linux system using pip. commands are:

#sudo apt-get install python-pip
#sudo pip install paramiko



#Importing modules
import paramiko
import sys
import time

#setting parameters like host IP, username, passwd and number of iterations to gather cmds
HOST = ""
USER = "admin"
PASS = "passwd"

#A function that logins and execute commands
def fn():
  #Add missing client key
  #connect to switch
  print "SSH connection to %s established" %HOST
  #Gather commands and read the output from stdout
  stdin, stdout, stderr = client1.exec_command('show version\n')
  stdin, stdout, stderr = client1.exec_command('show alarms | no-more\n')
  stdin, stdout, stderr = client1.exec_command( 'show processes memory | no-more\n')
  print "Logged out of device %s" %HOST

#for loop to call above fn x times. Here x is set to 3
for x in xrange(ITERATION):
  print "%s Iteration/s completed" %(x+1)
  print "********"
  time.sleep(5) #sleep for 5 seconds

The script is self explainable with comments added for clarity.

This entry was posted in Scripting and tagged , , , , . Bookmark the permalink.

5 Responses to Python Script that SSH to a switch and execute commands for ‘x’ times

  1. Ravi says:

    I don’t see “print” printed out in the output


  2. Md. Shamim akter Limon says:

    exe commad no 2 not execute


  3. Murray King says:

    You need to add “sudo apt-get install python-cffi” so command line instructions become:

    sudo apt-get install python-pip
    sudo apt-get install python-cffi
    sudo pip install paramiko

    This code was written for version 2 Python so brackets are needed on the PRINT commands and paramiko only runs on Python 2.


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 )

Google photo

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