Feb. 04, 2013

SSH Connection with Python

Overview

Last week I wrote an article about the pexpect module in Python and how you can
use it to take care of some of the automation needs, like ssh and ftp.
I would like to continue on that topic and write about it's pxssh class. 

With the pxssh module, it's easy to access other servers over SSH.

This article is based on the official documentation found here:
http://pexpect.sourceforge.net/pxssh.html

What is pxssh?

Pxssh is based on pexpect. It's class extends pexpect.spawn to specialize setting
up SSH connections. I use pxssh frequently for making ssh connections in python.

Module documentation

Open up a terminal and type in the following commands to get help about the module

import pxssh
help(pxssh)

Help on module pxssh:

NAME
   pxssh

FILE
   /usr/lib/python2.7/dist-packages/pxssh.py

DESCRIPTION
   This class extends pexpect.spawn to specialize setting up SSH connections.
   This adds methods for login, logout, and expecting the shell prompt.
    
   $Id: pxssh.py 513 2008-02-09 18:26:13Z noah $

CLASSES
   pexpect.ExceptionPexpect(exceptions.Exception)
       ExceptionPxssh
   pexpect.spawn(__builtin__.object)
       pxssh
You can also see the help here http://pexpect.sourceforge.net/pxssh.html

Methods and login process

Pxssh adds methods for login, logout, and expecting the shell prompt. 

It does various tricky things to handle many situations in the SSH login process. 

For example, if the session is your first login, then pxssh automatically accepts
the remote certificate; or if you have public key authentication setup then pxssh
won't wait for the password prompt.

How does pxssh works?

pxssh uses the shell prompt to synchronize output from the remote host. 

In order to make this more robust it sets the shell prompt to something more
unique than just $ or #. This should work on most Borne/Bash or Csh style
shells.

Example

 
This example runs a few commands on a remote server and prints the result. 

First we import the modules that we need. (pxssh and getpass)

We import the getpass module, which will prompt the user for a password,
without echoing what they type to the console.
 
import pxssh
import getpass
try:                                                            
    s = pxssh.pxssh()
    hostname = raw_input('hostname: ')
    username = raw_input('username: ')
    password = getpass.getpass('password: ')
    s.login (hostname, username, password)
    s.sendline ('uptime')   # run a command
    s.prompt()             # match the prompt
    print s.before          # print everything before the prompt.
    s.sendline ('ls -l')
    s.prompt()
    print s.before
    s.sendline ('df')
    s.prompt()
    print s.before
    s.logout()
except pxssh.ExceptionPxssh, e:
    print "pxssh failed on login."
    print str(e)

Run a command on a remote SSH server

Let's show one more example. To run a command ('uptime') and to print the output, 
you need to do something like that :
import pxssh
s = pxssh.pxssh()
if not s.login ('localhost', 'myusername', 'mypassword'):
    print "SSH session failed on login."
    print str(s)
else:
    print "SSH session login successful"
    s.sendline ('uptime')
    s.prompt()         # match the prompt
    print s.before     # print everything before the prompt.
    s.logout()
    
#We can also execute multiple command like this:
s.sendline ('uptime;df -h')
For more information about pxssh, please see the official documentation


Read more about: