Skip to content

Instantly share code, notes, and snippets.

@pajtai
Last active August 29, 2015 14:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pajtai/b04191fab0aa1fd4f7ba to your computer and use it in GitHub Desktop.
Save pajtai/b04191fab0aa1fd4f7ba to your computer and use it in GitHub Desktop.
Robust way of opening an closing ssh tunnels without having to depend on active connections
#!/usr/bin/env bash
#set -x # for debugging
SSH_HOST="user@www.sample.com"
# using -f and -o exitOnForwardFailure is helpful, but if you are managing processes that restart and you want to keep
# the tunnel open even after a restart this can be difficult (e.g. nodemon with a remote mongo, mysql, elasticsearch, etc)
#
# instead you can open the tunnels and close them on script exit
echo "opening ssh tunnels"
(ssh -N -L 27018:localhost:27017 -M -S /tmp/ssh_tunnel_27018_%h.sock $SSH_HOST)&
(ssh -N -L 9200:localhost:9200 -M -S /tmp/ssh_tunnel_9200_%h.sock $SSH_HOST)&
function finish {
echo "closing ssh tunnels"
ssh -S /tmp/ssh_tunnel_27018_%h.sock -O exit $SSH_HOST
ssh -S /tmp/ssh_tunnel_9200_%h.sock -O exit $SSH_HOST
}
trap finish EXIT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment