carlessanagustin
12/9/2016 - 1:53 PM

PYTHON/SSH: Connect to remote servers and run commands

PYTHON/SSH: Connect to remote servers and run commands

#!/usr/bin/python

import sys
from subprocess import call

ssh_commands = {
    'instance1': 'ssh -i "my.pem" user@fqdn',
    'instance2': 'ssh user@fqdn -i ~/.ssh/my.pem -o ProxyCommand="ssh -i ~/.ssh/my.pem -W %h:%p -q user@fqdn"',
    'instance3': 'ssh user@fqdn',
    'instance4': 'sshpass -p my_password_here ssh -o PubkeyAuthentication=no -o StrictHostKeyChecking=no -o ServerAliveInterval=60 user@fqdn'
}

arguments = len(sys.argv)

if arguments == 1:
    print "Posibilities: "
    for title in ssh_commands:
        print "  - " + title
elif arguments == 2:
    call([ssh_commands[sys.argv[1]]], shell=True)
else:
    command = ssh_commands[sys.argv[1]].split(" ")
    command.append("-t")
    command += sys.argv[2:]
    call([' '.join(command)], shell=True)