SSH Tunnel Script with Commented Usage Example

Useful script for accessing an unexposed port when you only have access to ssh on a server for debug purposes.

########################################
### BEGIN USAGE EXAMPLE FOR COPYING  ###
########################################

##########################################################################
### Usage Example, Copy the below into a separate script and uncomment ###
##########################################################################

#REMOTE_ADDRESS=8.8.8.8
#REMOTE_SSH_PORT=2020
#REMOTE_USERNAME=root
#REMOTE_PASSWORD=password

#declare -A DESTINATION_LIST
#DESTINATION_LIST+=(["5902"]="localhost:5902")

#sh tunnelOpen.sh "$REMOTE_ADDRESS" "$REMOTE_SSH_PORT" "$REMOTE_USERNAME" "$REMOTE_PASSWORD" "$(declare -p DESTINATION_LIST)"

########################################
### END USAGE EXAMPLE FOR COPYING  #####
########################################

REMOTE_ADDRESS=$1; shift
REMOTE_SSH_PORT=$1; shift
REMOTE_USERNAME=$1; shift
REMOTE_PASSWORD=$1; shift
eval "declare -A DESTINATION_LIST="${1#*=}

function establishTunnels()
{
    clear

    for LOCAL_LISTEN_PORT in "${!DESTINATION_LIST[@]}"
    do
        #Pull Values from Array
        DESTINATION_ADDRESS_DESTINATION_PORT=${DESTINATION_LIST[$LOCAL_LISTEN_PORT]}

        echo "Establishing Tunnel to $DESTINATION_ADDRESS_DESTINATION_PORT using Local Port $LOCAL_LISTEN_PORT"

        #ssh-keygen -R [$REMOTE_ADDRESS]:$REMOTE_SSH_PORT
        #ssh -o StrictHostKeyChecking=no -fNL $LOCAL_LISTEN_PORT:$DESTINATION_ADDRESS_DESTINATION_PORT -l root $REMOTE_ADDRESS -p $REMOTE_SSH_PORT >/dev/null 2>&1

        nohup echo y | "/c/Program Files/PuTTY/plink.exe" -N -L $LOCAL_LISTEN_PORT:$DESTINATION_ADDRESS_DESTINATION_PORT -ssh $REMOTE_USERNAME@$REMOTE_ADDRESS -P $REMOTE_SSH_PORT -pw $REMOTE_PASSWORD >/dev/null 2>&1 &

        echo ""
        echo "##################################################################"
        echo "If there are no errors up to this point you can now connect"
        echo "to the endpoint using localhost:$LOCAL_LISTEN_PORT using ssh/rdp"
        echo "##################################################################"
        echo ""
    done
}

establishTunnels

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s