Created
April 27, 2025 07:48
-
-
Save jbontech/7e7d6243885667575fe73b833c75b225 to your computer and use it in GitHub Desktop.
Create Revers SSH Tunnel from local ubuntu machine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
EC2_USER="sshtunnel" | |
EC2_HOST="your-ec2-public-ip" | |
EC2_PORT="22" | |
REMOTE_PORT="2222" | |
LOCAL_PORT="22" | |
KEY_PATH="/etc/sshtunnel/id_rsa" | |
sudo mkdir -p /etc/sshtunnel | |
sudo chmod 700 /etc/sshtunnel | |
sudo ssh-keygen -q -N "" -f $KEY_PATH | |
echo "Copying public key to EC2 instance..." | |
ssh-copy-id -i ${KEY_PATH}.pub -p $EC2_PORT $EC2_USER@$EC2_HOST | |
SERVICE_FILE="/etc/systemd/system/sshtunnel.service" | |
sudo bash -c "cat > $SERVICE_FILE" <<EOL | |
[Unit] | |
Description=Persistent Reverse SSH Tunnel to EC2 | |
After=network-online.target | |
Wants=network-online.target | |
[Service] | |
Type=simple | |
ExecStart=/usr/bin/ssh -i $KEY_PATH \\ | |
-o ServerAliveInterval=30 \\ | |
-o ServerAliveCountMax=3 \\ | |
-o ExitOnForwardFailure=yes \\ | |
-o StrictHostKeyChecking=no \\ | |
-o UserKnownHostsFile=/dev/null \\ | |
-N -T -R $REMOTE_PORT:localhost:$LOCAL_PORT $EC2_USER@$EC2_HOST | |
Restart=always | |
RestartSec=60 | |
[Install] | |
WantedBy=multi-user.target | |
EOL | |
sudo systemctl daemon-reload | |
sudo systemctl enable sshtunnel.service | |
sudo systemctl start sshtunnel.service | |
echo "Reverse SSH tunnel setup complete." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment