Here is such configuration from one of the servers that I maintain. The configuration uses systemd service which is created at the client side. Also it uses autossh, so as first step we need to install it.
sudo apt install autossh
Then create SSH configuration file.
sudo nano /etc/ssh/ssh_config.d/auto-ssh-systemd-hosts.conf
Host reverse.server-name.com
HostName 192.168.1.199
IdentityFile /root/.ssh/server-name.com/id_rsa
User User
Port 2222
LocalForward 22 127.0.0.1:2222
RemoteForward 2222 127.0.0.1:22
GatewayPorts yes
Compression yes
- Note the SSH key is possession of the root user, because it will be the owner of the service.
- Don't forget to change the parameters Host, HostName and IdentityFile.
- Here is assumed the ssh-server at the both systems listen to the custom port 2222.
At this stage you should be able to:
sudo ssh reverse.server-name.com # or
sudo autossh reverse.server-name.com
Finally create the service.
sudo nano /etc/systemd/system/autossh-reverse-server-name.service
[Unit]
Description=Keeps an SSH tunnel to 'server-name.com' open
After=network-online.target
[Service]
User=root
ExecStart=/usr/bin/autossh -M 0 -N -q -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" reverse.server-name.com
ExecStop=/usr/bin/killall -s KILL autossh
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
- Replace server-name.com and reverse.server-name.com with the actual values.
Now enable and start the service.
sudo systemctl daemon-reload
sudo systemctl enable autossh-reverse-server-name.service
sudo systemctl start autossh-reverse-server-name.service
In order to stop and disable the service.
sudo systemctl stop autossh-reverse-server-name.service
sudo systemctl disable autossh-reverse-server-name.service
You can get the status or restart the service by the following commands.
sudo systemctl status autossh-reverse-server-name.service
sudo systemctl restart autossh-reverse-server-name.service
The service will be restarted automatically if it hangs. On the other hand autossh will keep it alive much longer than ssh, because it also detects automatically the connection's failures.
References:
Once the service is started you should be able to:
user@server-name.com:~$ ssh localhost -p 22 # connect to the local-machine
user@local-machine:~$ ssh localhost -p 22 # connect to server-name.com
Of course you will need to provide correct authentication data to the commands.