SSH Reverse Tunnel Script Guide

AUTOMATION • NETWORKING • BASH • SECURITY

This automated Bash utility establishes a persistent, monitored reverse SSH tunnel with automatic key detection, failure exit behavior, and keep-alive intervals to maintain remote access connectivity without dropping connections.

The SSH Tunnel Script

Save the following script to /usr/local/bin/ssh-tunnel.sh and make it executable:

#!/bin/bash
# Path: /usr/local/bin/ssh-tunnel.sh

if [ "$#" -lt 3 ] || [ "$#" -gt 4 ]; then
    echo "Usage: $0 <local_port> <remote_user@remote_host> <remote_port> [path_to_ssh_key]"
    exit 1
fi

LOCAL_PORT="$1"
REMOTE_TARGET="$2"
REMOTE_PORT="$3"
SSH_KEY_PATH="$4"

DEFAULT_KEY_1="$HOME/.ssh/id_rsa"
DEFAULT_KEY_2="$HOME/.ssh/id_ed25519"

if [ -z "$SSH_KEY_PATH" ]; then
    if [ -f "$DEFAULT_KEY_1" ]; then
        SSH_KEY_PATH="$DEFAULT_KEY_1"
    elif [ -f "$DEFAULT_KEY_2" ]; then
        SSH_KEY_PATH="$DEFAULT_KEY_2"
    else
        echo "Error: No default SSH keys found at $DEFAULT_KEY_1 or $DEFAULT_KEY_2."
        echo "You must explicitly supply the path to your SSH key as the fourth argument."
        exit 1
    fi
else
    if [ ! -f "$SSH_KEY_PATH" ]; then
        echo "Error: Specified SSH key file does not exist at: $SSH_KEY_PATH"
        exit 1
    fi
fi

exec /usr/bin/ssh -N -R "${REMOTE_PORT}:localhost:${LOCAL_PORT}" -i "$SSH_KEY_PATH" -o "ExitOnForwardFailure=yes" -o "ServerAliveInterval=60" -o "ServerAliveCountMax=3" -o "StrictHostKeyChecking=accept-new" "$REMOTE_TARGET"

Usage and Execution

Run the script directly from the terminal by providing your local application port, the remote user and hostname, and the remote binding port:

chmod +x /usr/local/bin/ssh-tunnel.sh
/usr/local/bin/ssh-tunnel.sh 80 user@remote-server.com 8080