To access my Raspberry Pi at home without port forwarding on my modem (I do not have static IP address) I needed to set a persistent reverse ssh connection to my remote server. Then I found out that most promising soluting is to use program called
autossh. You can easily install it to Debian or Raspberry Pi by
apt-get install autossh
Instructions are applicable for other Linux distros, as well.
You can google and find lots of websites showing how to setup autossh or reverse ssh tunnelling. What I will tell you is how to create a systemd service for automatic reverse ssh connection to a remote host.
I assume you can access your remote server over ssh without password, otherwise this autossh service does not work. It is easy to set passwordless login to remote servers if you add your client's public rsa key to remote's authorized keys.
ssh-copy-id command does this trick easily for you.
Systemd services are easier and better than
init.d scripts so here is the service file I use to make reverse ssh tunnelling to my cloud server.
[Unit] Description=Reverse ssh tunnel After=network-online.target [Service] Restart=on-failure RestartSec=3 Environment="AUTOSSH_GATETIME=0" ExecStart=/usr/bin/autossh -M 0 -N -q -o "ExitOnForwardFailure yes" -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -p 22 -R 2222:localhost:22 email@example.com [Install] WantedBy=multi-user.target
This configuration will create a rock solid persistent reverse ssh connection to your remote host. It will try to connect to remote server whenever the connection fails somehow and you do not encounter any problem.
ExecStart option does the execution of the autossh with appropriate parameters. You should change the autossh and ssh parameters for your needs.
-R 2222:localhost:22 is the key parameter to make remote port forwarding (reverse). Remote port forwarding means that opening a listening socket on remote site (2222 in this case) and forwarding incoming packets to the client's port (22 in this case). When I connect to my cloud server and run
ssh -p 2222 [email protected] code, I can connect to my Raspberry Pi over ssh. This link has some information about ssh forwarding.
Copy this file
/lib/systemd/system/ folder and change the owner and permissions like this
chown root autossh.service chmod 0644 autossh.service
After that you need to enable the service and start
systemctl enable autossh.service systemctl start autossh.service
If you want to check the status of the service or disable it;
systemctl status autossh.service systemctl disable autossh.service
I saw many websites providing reverse ssh services for reasonable prices but there are also lots of cheap cloud server providers like
scaleway so you can setup your own secret tunnel on your own.
Have fun and let me know if you need more information about this subject.