Skip to content

Instantly share code, notes, and snippets.

@andrewbolster
Created August 28, 2015 11:39
Show Gist options
  • Save andrewbolster/811448482c9d52d5ca10 to your computer and use it in GitHub Desktop.
Save andrewbolster/811448482c9d52d5ca10 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Example script to start up tunnel with autossh.
# This script will tunnel 22 from the local host
# to 11122 on the remote host. If that post isn't
# availabile it'll increment. Also does the same
# with 8888/11188 for ipython notebook
# REQUIRED autossh
HOST=${@: -1}
REMOTE_SSH_PORT=11122
REMOTE_HTTP_PORT=11188
AUTOSSH_GATETIME=30
AUTOSSH_DEBUG=yes
AUTOSSH_PATH=/usr/bin/ssh
export AUTOSSH_GATETIME AUTOSSH_DEBUG AUTOSSH_PATH
OCCUPIED_PORTS=`ssh $HOST 'netstat -tln' | awk '$4~/0\.0\.0\.0:+*/{print $4}'| awk -F':' '{print $2}' | sort -n`
while [[ $OCCUPIED_PORTS =~ $REMOTE_SSH_PORT ]]; do
echo "${REMOTE_SSH_PORT} is taken"
REMOTE_SSH_PORT=$((REMOTE_SSH_PORT+1))
done
while [[ $OCCUPIED_PORTS =~ $REMOTE_HTTP_PORT ]]; do
echo "${REMOTE_HTTP_PORT} is taken"
REMOTE_HTTP_PORT=$((REMOTE_HTTP_PORT+1))
done
autossh -2 -fN -R '*':${REMOTE_SSH_PORT}:localhost:22 -R '*':${REMOTE_HTTP_PORT}:localhost:8888 $*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment