Skip to content

Instantly share code, notes, and snippets.

@pajtai
Last active August 29, 2015 14:25

Revisions

  1. pajtai revised this gist Jul 27, 2015. No changes.
  2. pajtai revised this gist Jul 27, 2015. 1 changed file with 6 additions and 4 deletions.
    10 changes: 6 additions & 4 deletions open-and-keep-alive.sh
    Original file line number Diff line number Diff line change
    @@ -1,19 +1,21 @@
    #!/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 user@www.sample.com)&
    (ssh -N -L 9200:localhost:9200 -M -S /tmp/ssh_tunnel_9200_%h.sock user@www.sample.com)&
    (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 user@www.sample.com
    ssh -S /tmp/ssh_tunnel_9200_%h.sock -O exit user@www.sample.com
    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
  3. pajtai created this gist Jul 27, 2015.
    19 changes: 19 additions & 0 deletions open-and-keep-alive.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    #!/usr/bin/env bash
    #set -x # for debugging

    # 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 user@www.sample.com)&
    (ssh -N -L 9200:localhost:9200 -M -S /tmp/ssh_tunnel_9200_%h.sock user@www.sample.com)&

    function finish {
    echo "closing ssh tunnels"
    ssh -S /tmp/ssh_tunnel_27018_%h.sock -O exit user@www.sample.com
    ssh -S /tmp/ssh_tunnel_9200_%h.sock -O exit user@www.sample.com
    }

    trap finish EXIT