SSH – Permanent Background SSH Connection for Reverse Tunnel

background-processssh

Related question: initiate ssh connection from server to client

Answer from there helped me a lot, this command does what I need:

ssh -R 2225:localhost:22 loginOfServerWithPublicIP@publicIP

So I wrote the script to reconnect all the time:

 #!/bin/bash

 while true; do
    echo "try to connect..."
    ssh -o ServerAliveInterval=240 -R 2225:localhost:22 user@host
    echo "restarting in 5 seconds.."
    sleep 5
 done

And added it to the /etc/crontab. But I found out that works if only I execute it "by hand" from shell, but if it is called by cron, ssh connects and immediately finishes. (so, the script above reconnects all the time)

From man ssh, I found that for background connections I should call it with -n key, but it didn't help. Then, I just looked around for similar scripts and I found that it works if I call tail -f something, i.e. some "neverending" command, so I just created empty file /tmp/dummy_file and now my ssh command looks like this:

ssh -o ServerAliveInterval=240 -R 2225:localhost:22 -n user@host tail -f /tmp/dummy_file

It works now! But, this solution seems a bit ugly, plus I don't really understand actual reasons of that behavior. Just by chance, I tried to call bash instead of tail -f (bash seems to me "neverending" command, too), but it doesn't work.

So, could anyone please explain this behavior, and what is the correct way to create background ssh connection to keep reverse ssh tunnel up?

Best Answer

It sounds like you want the -N option to ssh.

 -N      Do not execute a remote command.  This is useful for just forwarding ports
         (protocol version 2 only).
Related Question