Skip to content

Instantly share code, notes, and snippets.

@pconerly
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pconerly/0faeec7f94275c1736cb to your computer and use it in GitHub Desktop.
Save pconerly/0faeec7f94275c1736cb to your computer and use it in GitHub Desktop.
Rolling your own localtunnel
# this file lives in /project/app/management/commands/devtunnel.py
# it just spins up a localtunnel and retries it if it fails, until it gets a key command shutdown.
# you need to define some configuartion in your settings.py: SSH_TUNNEL_USER, SSH_SERVER_IP
# This assumes you're running your website on port 8070
import sys
import time
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
# Inspriation from http://code.activestate.com/recipes/576911-keep-a-process-up-and-running/
class Command(BaseCommand):
args = ''
help = 'Opens the dev tunnel based on your `settings_local.py`.'
def handle(self, *args, **options):
try: # if we have a SSH_TUNNEL_USER attribute in settings.py
user = "%s@" % settings.SSH_TUNNEL_USER
except AttributeError:
user = ''
cmd = """ssh %s%s \
-n -oExitOnForwardFailure=yes \
-oTCPKeepAlive=yes \
-oServerAliveInterval=2 \
-oStrictHostKeyChecking=no \
-R%s:127.0.0.1:%s idle.js""" % (
user,
settings.SSH_SERVER_IP,
settings.SSH_TUNNEL_PORT,
8070,
)
def start_subprocess():
return subprocess.Popen(cmd, shell=True)
try:
p = start_subprocess()
while True:
res = p.poll()
if res is not None:
print p.pid, 'was killed, restarting it'
p = start_subprocess()
else:
out, err = p.communicate()
# if out:
# print out
time.sleep(2)
except KeyboardInterrupt:
p.terminate()
#! /usr/bin/nodejs
// I put this in /usr/local/bin/idle.js
// This just exists to keep the tunnel up.
console.log("Welcome to the dev tunnel.")
var sleep = function(s) {
var e = new Date().getTime() + (s * 1000);
while (new Date().getTime() <= e) {
;
}
};
while(true) {
sleep(10);
console.log('.');
}
# add this to your nginx config for the person sshing in.
# The server name can be any subdomain
# the port in `proxy_pass` needs to match SSH_TUNNEL_PORT.
server {
listen 80;
listen 443 ssl;
server_name peter.dev.flaregun.io;
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://127.0.0.1:3020;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment