SSH for Python - In search of API perfection

Posted by Dave Tucker on Sun 16 March 2014

My mission is simple: Establish an SSH connection to a device and run some commands in as few lines as possible. The contenders? Paramiko, Spur and Fabric.

The Scenario

I have a network device, 192.168.1.254. I want to log in via SSH with a username of dave and password of p@ssword123. Once logged in, I want to execute the command display version and print the result.

Now to the code...

The Code

Paramiko

Paramiko is the go to SSH library in Python. Let's see how it shapes up in the simple scenario:

import paramiko
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
client.connect("192.168.1.254", username="dave", password="p@ssword123")
stdin, stdout, stderr = client.exec_command('display version')
for line in stdout:
    print line.strip('\n')
client.close()

8 lines of code. The API here is very powerful, but requires me to put up some scaffolding code (Key Management) before I actually get around to connecting an executing my command. That said, it gets the job done.

Spur

Spur is a wrapper around Paramiko that simplifies the API:

import spur
shell = spur.SshShell(hostname="192.168.1.254",
                      username="dave",
                      password="p@ssword123")
with shell:
    result = shell.run("display version")
print result.output

5 lines of code. Short and concise.

Spur also allows you to execute commands locally using the same interface, which is pretty cool!

Fabric

Fabric is both a Python library and a command line tool. It's aim is to streamline SSH usage for application deployment and system administration tasks. Here I create a fabfile.py that looks like this.

from fabric.api import run
def display_version():
    run("display version")

3 lines of code. Not bad at all! To run this on my remote host:

fab display_version -H dave@192.168.1.254

This is just scratching the surface of what Fabric can do. Fabric offers a great way of organizing tasks and executing them either locally or (on one or many) remote hosts.

The Verdict

The right tool for the job depends on the job itself:

  • If I'm writing some library code that needs a very rich SSH API, Paramiko wins.
  • If I only need a basic SSH API, Spur is a great choice!
  • If I have network devices to configure and want to build configuration files (using a templating system like Jinja2) and to deploy them, then Fabric is, in my opinion, the best tool for the job.

@dave_tucker


Comments !