Don't do this with cron. The best is to add a systemd service. For example, for the similar problem I use the unit file which looks like the following:
[Unit]
Description=forward public port 9944 to local 9922 with SSH
After=network-online.target
Wants=network-online.target
[Service]
ExecStart=ssh -i /root/.ssh/forwarder -g -L 0.0.0.0:9944:localhost:9922 localhost -o ExitOnForwardFailure=yes -N
Restart=always
RestartSec=60
[Install]
WantedBy=multi-user.target
Save this as /etc/systemd/system/ssh-forward-9944-to-9922.service
and execute
systemctl enable ssh-forward-9944-to-9922.service
systemctl start ssh-forward-9944-to-9922.service
Notice I added exit on forward failure option so if something claims that port the systemd will properly recognize this unit as failed. Notice also global bind option, to actually accept connections from other hosts, because despite your attempt to bind it to 0.0.0.0
, that will not work unless you enable it with -g
.
Finally, you have to setup keys properly. The unit file above is constructed so that the ssh client will be run as root and it will connect to localhost as root which means you need to have PermitRootLogin yes
or better, PermitRootLogin prohibit-password
(the default, the same thing as older spelling without-password
) in /etc/ssh/sshd_config
. The private key must be stored unencrypted as /root/.ssh/forwarder
. The public key should go into /root/.ssh/authorized_keys
.
The best is to use a dedicated key, generate it with
ssh-keygen -t ed25519 -f /root/.ssh/forwarder
(hit <Enter>
twice for no passprase). Then append the contents of the public counterpart to authorized_keys
with
cat /root/.ssh/forwarder.pub >> /root/.ssh/authorized_keys
Edit /root/.ssh/authorized_keys
to restrict this key (the last line) heavily, similar to the following:
restrict,port-forwarding,command="/bin/false" ssh-ed25519 AA[key contents follows]7b localhost port forwarder
just add this restrict,...
magic spell before your ssh-ed25519 ...
in the last line. You may enhance it further, for example, add from="127.0.0.1,::1",permitopen="127.0.0.1:9922",permitopen="[::1]:9922"
into restriction list (though I am not totally sure about correct spelling of IPv6 addresses in this file); read man authorized_keys
for details about this.