Using paramiko to send SSH commands

October 11, 2012

Reading time ~2 minutes

I’ve been coding a service which communicates over SSH today. I ran into a issue when trying to run long commands and listening to their output. It was kind of tiresome to find out all tricks to do, so here’s my code:

import sys
import time
import select
import paramiko

host = 'test.example.com'
i = 1

#
# Try to connect to the host.
# Retry a few times if it fails.
#
while True:
    print "Trying to connect to %s (%i/30)" % (host, i)

    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host)
        print "Connected to %s" % host
        break
    except paramiko.AuthenticationException:
        print "Authentication failed when connecting to %s" % host
        sys.exit(1)
    except:
        print "Could not SSH to %s, waiting for it to start" % host
        i += 1
        time.sleep(2)

    # If we could not connect within time limit
    if i == 30:
        print "Could not connect to %s. Giving up" % host
        sys.exit(1)

# Send the command (non-blocking)
stdin, stdout, stderr = ssh.exec_command("my_long_command --arg 1 --arg 2")

# Wait for the command to terminate
while not stdout.channel.exit_status_ready():
    # Only print data if there is data to read in the channel
    if stdout.channel.recv_ready():
        rl, wl, xl = select.select([stdout.channel], [], [], 0.0)
        if len(rl) > 0:
            # Print data from stdout
            print stdout.channel.recv(1024),

#
# Disconnect from the host
#
print "Command done, closing SSH connection"
ssh.close()

The code should be quite self explainatory, but here’s what it does in short:

  • Connect to the SSH server
  • Send the command (non-blocking)
  • Create a loop, waiting for the channel to get an exist code
  • The loop is looking for data to pring (stdout.channel.recv_ready()) and prints any data it receives

Running vim-airline with Maximum Awesome

I use [Maximum Awesome](https://github.com/square/maximum-awesome) when I code in [vim](http://www.vim.org/), it's a great starting place...… Continue reading

Quicksort implementation in Python

Published on August 04, 2014

Fibonacci generator in Python

Published on August 04, 2014