#!/usr/bin/env bash
#
# Reverse SSH tunnel
#
# This script allows you to connect to a remote host that is creating the reverse SSH tunnel.
#
# Say you want to connect to Host A from Host C. You will use Host C as a bridge.
# 
# Execute this script from Host A and point it to Host B.
# From Host C, connect to hosts B and then execute ssh user@localhost -p chosen_port 
#
# Call this script from rc.local
#
# Gabriel Marques
# snortt@gmail.com
# qua fev 21 22:13:50 -03 2018
# 

# SSH User
SSH_USER="username_here"

# Remote host
# This is the host that will act as the bridge between the 2 connecting hosts
SSH_HOST="host_to_atc_as_the_link"

# Interval to check SSH execution
INTERVAL="30"

# Bridge Port
# This is the port where SSH listens on Host B (if not 22)
#BPORT="1983"
BPORT="22"

# The remote port open by Host A
RPORT="1234"

# The local port where SSH is running in Host A
LPORT="22"

# SSH arguments
SSH_ARGS="-p ${BPORT} -f -N -R"
SSH_TUNNEL=" ${RPORT}:localhost:${LPORT}"

# Check SSH execution every INTERVAL seconds
while true
do
    ISUP=$(ps ax | grep -E "ssh ${SSH_ARGS}" | grep -v "grep" 2> /dev/null)
    if [ -z "${ISUP}" ]; then
        echo -e "SSH not running. Calling it now..."
        ssh ${SSH_ARGS} ${SSH_TUNNEL} ${SSH_USER}@${SSH_HOST} > /dev/null 2>&1 & 
        echo -e "Reverse port: ${RPORT}"
    fi

    sleep ${INTERVAL}
done

