Monday, April 5, 2010

Python SSH with Paramiko quickly

A quick python script to SSH into a server and run a list of commands. Uses Paramiko (doc). Fedora has a package:
yum install python-paramiko
Assumes you are using RSA Public Key Authentication:
#!/usr/bin/python
import paramiko, os, getpass

# Variables
username = 'you'
host = 'your.server.com'
port = 22
key = '~/.ssh/id_rsa'
msg = "Enter passphrase for key '" + key + "': "
private_key_pass = getpass.getpass(prompt=msg)
private_key_file = os.path.expanduser(key)

# Connctions
pkey = paramiko.RSAKey.from_private_key_file(private_key_file,\
                                              private_key_pass)
transport = paramiko.Transport((host, port))
transport.connect(username = username, pkey = pkey)

# Commands
cmds = ['ls', 'ls /foo']
for cmd in cmds:
    channel = transport.open_session()
    channel.exec_command(cmd)
    output = channel.makefile('rb', -1).readlines()
    if output:
        print "Success:"
        print output
    else:
        print "Error:"
        print channel.makefile_stderr('rb', -1).readlines()

transport.close()

No comments: