Skip to content

Instantly share code, notes, and snippets.

@chicagobuss
Last active September 11, 2017 20:25
Show Gist options
  • Select an option

  • Save chicagobuss/be431a562ff7d4885c93312a3e4de09e to your computer and use it in GitHub Desktop.

Select an option

Save chicagobuss/be431a562ff7d4885c93312a3e4de09e to your computer and use it in GitHub Desktop.
SSH Tunnel Examples
# simple local port forwarding example for vault
# - exposes localhost:8200 to 10.20.30.40:8200 via bastion.internal.company
# - bastion.internal.company has to be able to reach 10.20.30.40:8200
ssh -M -S http_vault -fnNT -L 8200:10.20.30.40:8200 [email protected]
alias tunnel_http='ssh -L <host_a>:<port_a>:<host_c>:<port_c> -i ~/.ssh/id_rsa <host_b>'
where host_a:port_a is the host you're actually trying to hit from your local box
and host_b is the host you're able to ssh into from host_a
and host_c:port_c is the application you're trying to reach (and accessible via this ip/port from host_b)
# A better way to manage them:
alias tunnel_make_http_8888='ssh -M -S http_8888 -fnNT -L <host_a>:<port_a>:<host_c>:<port_c -i ~/.ssh/id_rsa <host_b>'
alias tunnel_check_http_8888='ssh -S http_8888 -O check <host_b>'
alias tunnel_stop_http_8888='ssh -S http_8888 -O exit <host_b>'
# An even better way to manage them:
function tunnelto(){
if [[ -z $5 ]]; then
echo 'Usage: ssh -M -S $5 -fnNT -L ${HOSTNAME}:$1:$3:$4 -i /home/username/.ssh/id_rsa $2';
return 1;
fi;
host0=$(host $(hostname) | awk '{print $4}')
host1=$2
host2=$3
port0=$1
port2=$4
name=$5
sshkey=${6:-/home/${USER}/.ssh/id_rsa}
sshuser=${7:-${USER}}
ssh -M -S $name -fnNT -L $host0:$port0:$host2:$port2 -i $sshkey $sshuser@$host1
}
function tunnelsrunning(){
ps x | grep 'ssh -M' | grep -v grep | awk '{print $8}'
}
function tunnelkill(){
ssh -S ${1} -O exit $(ps x | grep ssh | grep ${1} | awk '{print $NF}')
}
function tunnelkillall(){
for i in $(tunnelsrunning); do
tunnelkill ${i}
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment