paramiko: ssh scripting the ez way

The other day I wanted to jack around some goofy script and run it on a bunch of hosts, but… without keys, it was drag to do in a simple script… So… a buddy of mine had used paramiko to do some ssh action in python.

After reading Jesse‘s article, I used paramiko to copy a script around, run it and collect the output on the local filesystem

Here is some crap example:

import os
import paramiko
import socket
import sys

# yeh... my script really doesn't look like this...

host = ''
username = 'root'
password = 'passwords_are_for_cowards'

tmp  = '/tmp/'

# copy our cool_script over to the host in /tmp
transport = paramiko.Transport( ( host, 22 ) )
transport.connect( username = username, password = password )
sftp = paramiko.SFTPClient.from_transport( transport )
sftp.put( '', tmp )

# seems like ssh.connect sometimes fails due to some
# weird dns issue, so hack around it...
ip = socket.gethostbyname( host )

# chmod and run the script
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() )
ssh.connect( ip, username = username, password = password )
stdin, stdout, stderr = ssh.exec_command( 'chmod 755 ' + tmp + ';' + tmp )
data =

# save the output as json on the local filesystem
filename = host + '.json'
output = open( filename, 'w' )
output.write( data )



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: