Last active
April 30, 2019 23:08
-
-
Save Benoss/21a1caf284da567460a8c805e416a8b6 to your computer and use it in GitHub Desktop.
Reverse tunnel local ssh to remote server on ubuntu and maintain it alive with systemd and autossh
This file contains 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
# On the remote machine create a user with no bash | |
sudo useradd -m -s /bin/false ssh_forwarder | |
# Take control of the user with bash | |
sudo -Hu ssh_forwarder /bin/bash | |
cd ~ | |
mkdir .ssh | |
ssh-keygen | |
chmod 700 .ssh/ | |
mv .ssh/id_rsa.pub .ssh/authorized_keys | |
chmod 600 .ssh/authorized_keys | |
chmod 600 .ssh/id_rsa | |
# copy the .ssh/id_rsa file to the local machine in /root/.ssh/ssh_forwarder_key | |
# create a /root/.ssh/config file with the tunnel content | |
Host iwant | |
HostName 82.83.126.95 | |
User ubuntu | |
RemoteForward 8022 localhost:22 | |
Compression yes | |
ExitOnForwardFailure yes | |
ServerAliveInterval 30 | |
ServerAliveCountMax 3 | |
# this will forward the local ssh to the remote port 8022 | |
# test on the local machine | |
ssh iwant_tunnel (This should connect and return because of /bin/false) | |
ssh -N iwant_tunnel should block | |
# while the ssh -N is still running try on the remote machine | |
telnet 127.0.0.1 8022 (This should show openssh protocol) | |
# install autossh (a prog that keeps alive ssh tunnels and restart them when they die) | |
sudo apt-get install autossh | |
# install a systemD service on the local machine for this autossh | |
# vim /etc/systemd/system/autossh-iwant-tunnel.service | |
[Unit] | |
Description=AutoSSH reverse tunnel service to iwant 22 to 8022 remote | |
After=network.target | |
[Service] | |
Environment="AUTOSSH_GATETIME=0" | |
ExecStart=/usr/bin/autossh -M 0 -N iwant | |
[Install] | |
WantedBy=multi-user.target | |
systemctl daemon-reload | |
systemctl start autossh-iwant-tunnel | |
systemctl status autossh-iwant-tunnel | |
● autossh-iwant-tunnel.service - AutoSSH reverse tunnel service to iwant 22 to 8022 remote | |
Loaded: loaded (/etc/systemd/system/autossh-moneyfit-tunnel.service; disabled; vendor preset: enabled) | |
Active: active (running) since Wed 2017-01-18 23:34:10 UTC; 13s ago | |
# you can add more tunnels in the /root/.ssh/config file by adding multiple RemoteForward | |
# restart the tunnel by doing | |
systemctl restart autossh-iwant-tunnel |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment