Skip to content

Instantly share code, notes, and snippets.

@carlessanagustin
Last active December 10, 2021 00:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlessanagustin/547d6f937e4d55c0d65e90027bf2ddcc to your computer and use it in GitHub Desktop.
Save carlessanagustin/547d6f937e4d55c0d65e90027bf2ddcc to your computer and use it in GitHub Desktop.
SSH reverse tunnel as systemd service
#!/usr/bin/env bash
: '
SOURCE node creates a tunnel to DESTINATION
This allows connections from DESTINATION to SOURCE with: ssh $USERNAME@localhost -p 19999
'
USERNAME=tunnel
PRIVKEY=/etc/tunnel/id_rsa
DESTINATION=ssh.example.com
cat << EOF | sudo tee /etc/systemd/system/sshtunnel.service
[Unit]
Description=SSH Tunnel
After=network.target
[Service]
Restart=always
RestartSec=20
# User=sshtunnel
ExecStart=/usr/bin/ssh -N -p 22 -o PubkeyAuthentication=yes -o ServerAliveInterval=60 -i $PRIVKEY -R 19999:localhost:22 $USERNAME@$DESTINATION
[Install]
WantedBy=multi-user.target
EOF
sudo chmod a+x /etc/systemd/system/sshtunnel.service
sudo chmod a+r /etc/systemd/system/sshtunnel.service
# sudo useradd sshtunnel
sudo systemctl enable sshtunnel.service
sudo systemctl start sshtunnel.service
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment