Created Sat Dec, 13 2025 at 07:46PM
If you need to ensure you have access to a server without having control over port forwarding, autossh is a great solution.
First start out by installing autossh and creating a systemd service to have it automatically start with the system.
sudo apt update && sudo apt install -y autossh
sudo vi /etc/systemd/system/tunnel.service
paste in the following updating the remote_user & remote_hostname in the example below.
[Unit]
Description=Establish persistent SSH tunnel
# Requires=ssh.service
Wants=network-online.target
After=network-online.target
[Service]
# User=local_user_if_needed
# Group=local_group_if_needed
# Environment=AUTOSSH_POLL=60 AUTOSSH_FIRST_POLL=30 AUTOSSH_LOGFILE=/var/log/autossh.log AUTOSSH_LOGLEVEL=7 AUTOSSH_GATETIME=0
# ExecStartPre=/usr/bin/sleep 10
ExecStart=/usr/bin/autossh -i /root/.ssh/id_rsa -N -M 0 -R 5522:localhost:22 -o 'PasswordAuthentication=no' -o 'PubkeyAuthentication=yes' -o 'ServerAliveInterval=30' -o 'ServerAliveCountMax=3' remote_user@remote_server
RestartSec=6
Restart=always
[Install]
WantedBy=multi-user.target
Next we'll need to login as whatever local_user really is, and generate ssh keys. Leave passwords blank when prompted to type in a password since we won't actually be able to type anything in for this to remain "automatic".
ssh-keygen -t rsa -b 4096
ensure the paths to the id_rsa files are what was shown in the service definition.
Finally, on the remote system you'll need to edit the ~remote_user:.ssh/authorized_hosts file and copy/paste in the contents of id_rsa.pub. To ensure this user can't do anything but ssh you can further switch remote_users shell to /bin/true.