Skip to content

Instantly share code, notes, and snippets.

@lfborjas
Created April 28, 2011 02:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lfborjas/945690 to your computer and use it in GitHub Desktop.
Save lfborjas/945690 to your computer and use it in GitHub Desktop.
Tunnel a local port to a remote host (like showoff.io does)
#!/usr/bin/python
#usage python show.py <local_port>
'''
Taken from: https://gist.github.com/932137 (found in http://news.ycombinator.com/item?id=2467107 )
Let's say you have a webapp running in localhost (with `manage.py runserver` in django or `ruby script.rb` in sinatra or `rails server` or whatever) and you want others to be able to see it with a public url without deploying remotely.
ssh provides a neat facility for that: tunneling. You set up a "tunnel" from the remote host to yours and vice-versa and then you give the remote host's url and it will send all of its requests to your local daemon.
You need *root* access to the remote host to configure how it will listen (I have a lighttpd conf that tells my server that `test.mydomain.com` should proxy to the port 4567, and I tunnel localhost there) and set-up the tunnel; I'd recommend using ssh public key authentication (you can copy your key with `ssh-copy-id`).
After configuring that (with apache, ngingx, lighttpd or anything), you can run your local script (say, a django app in localhost:8000) and then run this script:
python show.py 8000
And people will be able to see it from http://test.mydomain.com
'''
import sys, subprocess
remote = {
"host": 'ssh.domain.com', #how my ssh config knows that remote
"alias": 'test.domain.com', #the binding address to give to others
"port":'80', #where is the remote listening
"through":'2888' #the ssh port (is 22 by default, I have a nonstandard config)
}
port = sys.argv[1]
remote.update({'local_port': port})
print "Trying to tunnel local port %s to %s" % (port, remote["alias"])
command = "ssh -tR 1080:127.0.0.1:%(local_port)s %(host)s \"sudo ssh -Nl \$USER -L %(alias)s:%(port)s:127.0.0.1:1080 %(host)s -p %(through)s\"" % remote
subprocess.call(command, shell=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment