I would prefer to use the autossh
package for such service. So first install it:
sudo apt update && sudo apt install autossh
Then create configuration entry for your connection, by creating a new file within the directory /etc/ssh/ssh_config.d/
. Let's call it reverse.ssh.www.example.org.conf
. Here is an example:
sudo nano /etc/ssh/ssh_config.d/reverse.ssh.www.example.org.conf
# This file is loaded by /etc/ssh/ssh_config
Host reverse.ssh.www.example.org
HostName www.example.org
IdentityFile /root/.ssh/your_passles_id_rsa
User mum
Port 22
RemoteForward 19123 127.0.0.1:22
GatewayPorts yes
Compression yes
- Note the SSH key is possession of the root user who will manage the connection by our service.
- The last two options are not mandatory.
Finally create the service:
sudo nano /etc/systemd/system/reverse-autossh-www-example-org.service
[Unit]
Description=Keeps a resident tunnel to www.example.org open
#After=network.target
After=network-online.target
[Service]
User=root
ExecStart=/usr/bin/autossh -M 0 -N -q -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" reverse.ssh.www.example.org
ExecStop=/usr/bin/killall -s KILL autossh
#ExecStop=/bin/kill $MAINPID
Restart=always
RestartSec=3
#Environment=AUTOSSH_GATETIME=0
[Install]
WantedBy=multi-user.target
Enable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable reverse-autossh-www-example-org.service
sudo systemctl start reverse-autossh-www-example-org.service
I've used this configuration for last two years in order to solve similar task - it works like a charm. However, here are few references: