Categories
python

Using Python to Automate SSH Connection and Run Commands

We will be using a  http://fitztrev.github.io/shuttle/ and the pexpect python library.

Here is what the shuttle menu looks like. Mine could be named better.

Shuttle

#!/usr/bin/python
from pexpect import *
import pexpect
PROMPT = ['# ', '>>> ', '> ','\$ ']

def send_command(child, cmd):
    child.sendline(cmd)
    child.expect(PROMPT)
    print child.before
    child.interact()

def connect(user, host, password):
    ssh_newkey = 'Are you sure you want to continue connecting'
    connStr = 'ssh ' + user + '@' + host
    child = pexpect.spawn(connStr)
    ret = child.expect([pexpect.TIMEOUT, ssh_newkey,\
                        '[P|p]assword:'])
    
    if ret == 0:
        print '[-] Error Connecting'
        return
All the herbs in Night Fire capsule is responsible purchase levitra online http://new.castillodeprincesas.com/item-4987 for increasing semen load and male vitality. Apart from some side effects that are informed by medicine instructions, more  cheapest cialis in australia and more new side effects are found after patients regularly use it. Treatments like chiropractic manipulation, or manual manipulation from osteopathic doctors, physiatrists or other appropriately trained health professionals, can help reduce this pain by mobilizing painful joint dysfunction. vardenafil canadian pharmacy If the user have any issue to ingest the tablet form of the medicine then he can also opt for  levitra uk Kamagra 100 mg jelly which is contained in a sachet that is squeezed into the mouth.     
    if ret == 1:
        child.sendline('yes')
        ret = child.expect([pexpect.TIMEOUT, \
                            '[P|p]assword:'])
        if ret == 0:
            print '[-] Error Connecting'
            return
    
    child.sendline(password)
    child.expect(PROMPT)
    return child


def main():
    host = 'HOST'
    user = 'USERNAME'
    password = 'PASSWORD'
    
    child = connect(user, host, password)
    send_command(child, 'cd /home')

if __name__ == '__main__':
    main()