view scripts-java/scpall.py @ 117:fce61ee25d20

run FederatedLinda experiment on torque
author kazz
date Wed, 08 Feb 2012 18:02:00 +0900
parents cdc08d4722ec
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, dest_dir, password, file):
    """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.*'
#    ssh_newkey = '.*(yes/no)?.* '
    child = pexpect.spawn('scp -r '+file+' '+user+'@'+host+':'+dest_dir)
    i = child.expect([pexpect.TIMEOUT, ssh_newkey, '.*ssword:.*',
                      user+'@'+host+"'s password: "])
#    print user+'@'+host+"'s password: "
    while i:
        if i == 1: # SSH does not have the public key. Just accept it.
            child.sendline ('yes')
            child.expect ('.*ssword:*')
            i = child.expect([pexpect.TIMEOUT, '.*ssword:.*'])
        else:
            # send password
            child.sendline(password)
            return child
        
    print 'ERROR!'
    print 'SSH could not login. Here is what SSH said:'
    print child.before, child.after
    return None

def usage(program_name):
    print "Usage : %s [-l username] [-f hostlist] [-d dest_dir] file" % program_name
    sys.exit(1)


def main(user, hostlist, dest_dir, filename):

    # get password
    password = getpass.getpass('Password: ')

    childlist = []

    for host in hostlist:
        child = ssh_command(user, host, dest_dir, password, filename)
        print child.expect(pexpect.EOF)
#        print child.before
        if child is not None:
            print "".join(['send to ', user, '@', host, ':',dest_dir,' : ', filename])
            childlist.append(child)
        
# end main



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

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

# default
user = os.environ['USER']
hostlistfile = "hostlist"
dest_dir = "~"

for o, a in opts:
    if o == '-l':
        user = a
    elif o == '-f':
        hostlistfile = a
    elif o == '-d':
        dest_dir = a
    else:
        pass

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

# 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)

print hostlist

main(user, hostlist, dest_dir, filename)