SSH Tunnels

Bash script found here: https://gist.github.com/scy/6781836

 

  • -fRun in the background before command execution.
  • -NDon’t execute any commands
  • -TDisable pseudo-tty allocation.
  • -S socketnameUse a control socket with name socketname
  • -MPut control socket in master mode
  • -O check, exitControl command

 

#!/bin/bash

ip="1.1.1.1"

socket=$(mktemp -t deploy-ssh-socket)
rm ${socket} # delete socket file so path can be used by ssh

exit_code=0

cleanup () {
    # Stop SSH port forwarding process, this function may be
    # called twice, so only terminate port forwarding if the
    # socket still exists
    if [ -S ${socket} ]; then
        echo
        echo "Sending exit signal to SSH process"
        ssh -S ${socket} -O exit root@${ip}
    fi
    exit $exit_code
}

trap cleanup EXIT ERR INT TERM

# Start SSH port forwarding process for mariadb (3306) and postgresql (5432)
ssh -M -S ${socket} -fNT -L 3306:localhost:3306 -L 5432:localhost:5432 root@${ip}

ssh -S ${socket} -O check root@${ip}

# launching a shell here causes the script to not exit and allows you
# to keep the forwarding running for as long as you want.
# I also like to customise the prompt to indicate that this isn't a normal shell.

bash --rcfile <(echo 'PS1="\nwith-ports> "')