Paramiko python ssh library

At times we have to use ssh connections to remote hosts/devices in programs to perform certain tasks. Here is an example that you can pick and modify to your taste.


#!/bin/python
import paramiko
import sys

# Create ssh object

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# perform ssh login to host/device
try:
       ssh.connect(hostname_or_ip, port=22, username='username', password='password', look_for_keys=False, allow_agent=False)

# exit upon exception
except paramiko.SSHException:
       print "Connection Failed"
       quit()

# Issue commands on host/device after login, for eg ping
command="ping 192.168.0.23"
stdin,stdout,stderr = ssh.exec_command(command)

# Get output of excuted command in a buffer for further processsing
buffer=stdout.readlines()