Executing Multiple SSH Commands Using Python

There are many ways to do this. If you only want to run a few commands, then the Python subprocess  module might be best. If you are only working in Python 2.X, then Fabric might be best. Since I wanted 2.X or 3.X and I wanted to run lots of commands, I went with Paramiko. Here is the solution:

import paramiko

IDENTITY = 'path to private key'
REMOTE = 'url of remote'

k = paramiko.RSAKey.from_private_key_file(IDENTITY)
with paramiko.SSHClient() as ssh:
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(REMOTE, username='vagrant', pkey=k)
    for comand in commands:
        ssh.exec_command(command)

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s