Skip to content

Instantly share code, notes, and snippets.

@alanbriolat
Created October 11, 2011 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alanbriolat/1279710 to your computer and use it in GitHub Desktop.
Save alanbriolat/1279710 to your computer and use it in GitHub Desktop.
SSH tunnel script generator
#!/usr/bin/python
import getopt, sys, pprint
pp = pprint.PrettyPrinter(indent=4)
shortopts = 'h:l:r:'
locals = []
remotes = []
hosts = []
destination = None
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)
if 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) )))
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment