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?
&
at the end of your ssh command:ssh -o ServerAliveInterval=240 -R 2225:localhost:22 user@host &
while
loop will run again and again, starting new backgroundssh
connection every 5 seconds, right? This isn't what I need.