#!/usr/bin/python import getopt, sys, pprint shortopts = 'h:l:r:s' locals = [] remotes = [] hosts = [] destination = None shebang = False optlist, arglist = getopt.gnu_getopt(sys.argv[1:], shortopts) # Only allow one destination! if len(arglist) == 1: destination = dict(zip( ('host', 'port'), arglist[0].rsplit(':', 1) )) else: raise ValueError, "Provide a single destination host" # Get the ports and intermediate hosts for opt, val in optlist: if opt == '-l': port = dict(zip( ('local', 'mid', 'remote'), val.split(':', 2) )) locals.append(port) elif opt == '-r': port = dict(zip( ('remote', 'mid', 'local'), val.split(':', 2) )) remotes.append(port) elif opt == '-h': hosts.append(dict(zip( ('host', 'port'), val.rsplit(':', 1) ))) elif opt == '-s': shebang = True if shebang: print '#!/bin/bash -i' # If there are no intermediate hosts, do it the simple way! if len(hosts) == 0: forwards = [] for f in locals: forwards.append('-L%s:localhost:%s' % (f['local'], f['remote'])) for f in remotes: forwards.append('-R%s:localhost:%s' % (f['remote'], f['local'])) if destination.has_key('port'): print 'ssh', ' '.join(forwards), '-p', destination['port'], destination['host'] else: print 'ssh', ' '.join(forwards), destination['host'] # Here comes the complex way!!! else: first = ' '.join(['-L%s:localhost:%s' % (f['local'], f['mid']) for f in locals] \ +['-R%s:localhost:%s' % (f['mid'], f['local']) for f in remotes]) last = ' '.join(['-L%s:localhost:%s' % (f['mid'], f['remote']) for f in locals] \ +['-R%s:localhost:%s' % (f['remote'], f['mid']) for f in remotes]) mid = ' '.join(['-L%s:localhost:%s' % (f['mid'], f['mid']) for f in locals] \ +['-R%s:localhost:%s' % (f['mid'], f['mid']) for f in remotes]) def mkcmd(i, hostlist): slashes = '\\' * i if len(hostlist) == 0: if destination.has_key('port'): return '-p ' + destination['port'] + ' ' + destination['host'] else: return destination['host'] else: host = hostlist[0] port = ''; if host.has_key('port'): port = '-p ' + host['port'] + ' ' return '%s%s -t %s"ssh %s %s%s"' % (port, host['host'], slashes, [last,mid][len(hostlist) > 1], \ mkcmd(i+1, hostlist[1:]), slashes) print 'ssh', first, mkcmd(0, hosts)