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 = ''
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)

        ssh = paramiko.SSHClient()
        print "Connected to %s" % host
    except paramiko.AuthenticationException:
        print "Authentication failed when connecting to %s" % host
        print "Could not SSH to %s, waiting for it to start" % host
        i += 1

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

# 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
    # Only print data if there is data to read in the channel
        rl, wl, xl =[], [], [], 0.0)
        if len(rl) > 0:
            # Print data from stdout

# Disconnect from the host
print "Command done, closing SSH connection"

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 ( and prints any data it receives

Running vim-airline with Maximum Awesome

I use [Maximum Awesome]( when I code in [vim](, 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