Mercurial > hg > FederatedLinda
view scripts-java/sshandcmd.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, 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.*' child = pexpect.spawn('ssh -l %s %s'%(user, host), timeout=30) i = child.expect([pexpect.TIMEOUT, ssh_newkey, '.*ssword:.*']) while i: if i == 1: # SSH does not have the public key. Just accept it. child.sendline ('yes') i = child.expect([pexpect.TIMEOUT, ssh_newkey, '.*ssword:.*']) elif i == 2: # input password child.sendline(password) child.sendline(command) 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)