view scripts-java/sshcmd.py @ 1:cdc08d4722ec

scripts
author fuchita
date Thu, 07 Feb 2008 15:51:20 +0900
parents
children
line wrap: on
line source

#!/usr/bin/env python
'''This runs a COMMAND on a remote host using SSH.
    At the prompts enter password.
'''
import pexpect
import getpass

import getopt
import sys
import os
import re

def ssh_command (user, host, password, command):
    """This runs a command on the remote host. This returns a
    pexpect.spawn object. This handles the case when you try
    to connect to a new host and ssh asks you if you want to
    accept the public key fingerprint and continue connecting.
    """
    ssh_newkey = 'Are you sure you want to continue connecting.*'
    yesno = '.*yes/no.*'
    child = pexpect.spawn('ssh -l %s %s \"%s\"'%(user, host, command),
                          timeout=30)
    i = child.expect([pexpect.TIMEOUT, ssh_newkey, '.*ssword:.*', yesno])
    while i:
        if i in (1,3): # SSH does not have the public key. Just accept it.
            child.sendline ('yes')
#            child.expect ('.*ssword:*')
            i = child.expect([pexpect.TIMEOUT, ssh_newkey, '.*ssword:.*',yesno])
        elif i == 2:
            # input password
            child.sendline(password)
            return child
        else:
            print child.before, child.after

    print 'ERROR!'
    print 'SSH could not login. Here is what SSH said:'
    print child.before, child.after
    return None

def gethostlist(hostlistfile):

    # get host name list from file
    hostlist = re.split('\s+', open(hostlistfile).read())

    if hostlist[-1] == '':
        hostlist.pop()

    if hostlist[0] == '':
        hostlist.pop(0)

    dellist = []
    for h in hostlist:
        if h[0] == '#':
            print "remove",h
            dellist.append(h)

    for d in dellist:
        hostlist.remove(d)
        
    return hostlist


def main(user, hostlist, command, waitprc=False):
    # get password
    password = getpass.getpass('Password: ')

    childlist = []

    if not waitprc:
        command = command + ' &'

    for host in hostlist:
        child = ssh_command(user, host, password, command)
        if child is not None:
            print "".join([user, '@', host, ' : ', command])
            childlist.append(child)
            if waitprc:
                print child.expect(pexpect.EOF)
                print child.before

# end main


def usage(program_name):
    print "Usage : %s [-w] [-h hostname] [-l username] [-f hostlist] command" % program_name
    sys.exit(1)


if __name__ == "__main__":
    if (len(sys.argv) < 2) :
        usage(sys.argv)

try:
    opts, args = getopt.getopt(sys.argv[1:], "h:l:f:w")
except getopt.GetoptError:
    usage(sys.argv[0])

# default
user = os.environ['USER']
hostlist = ["localhost"]
waitprc = False

for o, a in opts:
    if o == '-l':
        user = a
    elif o == '-w':
        waitprc = True  # show children's output
    elif o == '-f':
        hostlist = gethostlist(a)
    elif o == '-h':
        hostlist = [a]
    else:
        pass

# execute command on remote host
command = args[0]

main(user, hostlist, command, waitprc)