BASH
Create a Secure SSH Tunnel for Local Port Forwarding
Establish a secure SSH tunnel to forward a remote port to a local port, enabling access to services on a remote network as if they were local.
#!/bin/bash
# Configuration
REMOTE_HOST="your_remote_server.com" # The remote server's hostname or IP
REMOTE_USER="ssh_user" # Your SSH username on the remote server
REMOTE_SERVICE_IP="127.0.0.1" # IP of the service on the remote server (often localhost relative to the SSH server)
REMOTE_SERVICE_PORT="3306" # The port of the service on the remote server (e.g., MySQL)
LOCAL_LISTEN_PORT="3307" # The local port you want to use to access the service
# Optional: Path to your SSH private key
# SSH_KEY="~/.ssh/id_rsa"
# Check if SSH is installed
if ! command -v ssh &> /dev/null
then
echo "SSH client could not be found. Please install OpenSSH client."
exit 1
fi
echo "Attempting to establish SSH tunnel..."
echo "Local access: localhost:$LOCAL_LISTEN_PORT -> $REMOTE_HOST:$REMOTE_SERVICE_PORT"
# Construct SSH command for local port forwarding (-L)
# -N: Do not execute a remote command.
# -T: Disable pseudo-terminal allocation.
# -L: Local port forwarding: [local_port]:[remote_host]:[remote_port]
# -f: Go to background after authentication (optional, useful for daemonizing)
# -q: Quiet mode
# -i: Specify identity file (private key)
SSH_COMMAND="ssh -N -L $LOCAL_LISTEN_PORT:$REMOTE_SERVICE_IP:$REMOTE_SERVICE_PORT $REMOTE_USER@$REMOTE_HOST"
# if [ -n "$SSH_KEY" ]; then
# SSH_COMMAND="$SSH_COMMAND -i '$SSH_KEY'"
# fi
# Run in background with `&` or foreground without it
$SSH_COMMAND &
if [ $? -eq 0 ]; then
echo "SSH tunnel established. You can now connect to localhost:$LOCAL_LISTEN_PORT."
echo "To terminate the tunnel, find the process ID (ps -ef | grep ssh) and kill it."
else
echo "Failed to establish SSH tunnel. Check your SSH configuration and credentials."
exit 1
fi
How it works: This script creates a secure SSH tunnel using local port forwarding. It maps a port on your local machine (`LOCAL_LISTEN_PORT`) to a specific port on a remote server (`REMOTE_SERVICE_PORT`). This allows you to securely access services running on the remote server (e.g., a database like MySQL or PostgreSQL, or a web service not directly exposed) as if they were running locally. The `-N` flag prevents executing remote commands, and `-L` defines the port forwarding. Running it in the background (`&`) is convenient for continuous access during development.