Skip to content

Instantly share code, notes, and snippets.

@mrcodetastic
Created November 20, 2024 22:28
Show Gist options
  • Save mrcodetastic/4809d8fc1ac0d916b96dfce8aeb39a62 to your computer and use it in GitHub Desktop.
Save mrcodetastic/4809d8fc1ac0d916b96dfce8aeb39a62 to your computer and use it in GitHub Desktop.
VNC to a host behind NAT using a VPS and SSH
#!/bin/bash
# Run this script on a client computer that needs to connect to a VPS (using a ssh key), and uses a forwarded SSH port
# that exists on that VPS (from the client that is behind NAT) to connect to the SSH server on the final client,
# and uses that connection to forward local ports via the overall-SSH connection that is passing via the VPS.
#
# Client (forwards port 2201 on the VPS at 2202 locally) -> NAT -> VPS <- NAT <- Host (forwards port 22 as Port 2201 on the VPS)
# Connecting to 'localhost' on port '2202' on the client, is the same as connecting to port 22 on the Host.
#
# Requirements
# SSH key setup on both VPS and Ultimate Host to avoid interactive login steps.
# DIY alternative to using ZeroTier (but not free)
# Killall
echo "Killing any existing ssh"
killall ssh
# Execute the first SSH command to connect to VPS
echo "Starting first SSH tunnel..."
ssh -i ~/.ssh/client_rsa_key -p 22 vps_user@vps_host.name -L 2202:localhost:2201 -o ServerAliveInterval=3 -N &
SSH_TUNNEL_PID1=$!
sleep 5
# Execute the second SSH command to connect to ultimate host hidden behind NAT
# Forward the x11vnc server's ports to locally
echo "Starting second SSH tunnel..."
ssh -p 2202 nat_host_user@localhost -i ~/.ssh/client_rsa_key -L 5900:localhost:5900 "x11vnc -display :0 -forever" &
SSH_TUNNEL_PID2=$!
sleep 8
# Trap to clean up background processes
trap "echo 'Stopping tunnels and VNC client...'; kill $SSH_TUNNEL_PID1 $SSH_TUNNEL_PID2" SIGINT SIGTERM
# Wait for processes to end
wait
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment