For many days, I've wondered how to automate the establishment of a reverse tunnel.
I've many remote Raspberry using NAT inside their LANs, and one Raspberry that I use as server, reachable from the Internet.
I've implemented on my website a system to send to remote Raspberries single commands.
Every remote Raspberry checks every minute (crontab) the presence of commands available, and if is there is one, then it downloads the command, creates an executable file and runs it. Here is the code of the crontab file:
#! /bin/bash
sudo wget -c --output-document=ipdiscover.php "www.myserver.com/checkforcommands.php";
comando=$(cat ipdiscover.php);
sudo rm "/esegui.sh";
echo "#! /bin/bash" >> /esegui.sh;
echo "" >> /esegui.sh;
echo -e $comando >> /esegui.sh;
echo "exit 0" >> /esegui.sh;
sudo chmod +x /esegui.sh;
sudo /esegui.sh;
sudo rm "ipdiscover.php";
sudo date >>/tmp/crontest.txt;
This system functions very well, but I can't use it to establish the reverse tunnel.
If, on remote server, I run this code:
sudo /usr/bin/ssh -gNnT -R 2222:localhost:22 pi@publicserverIP;
then all works correctly, but if I run it from the crontab script, it does not work.
I created the certificates without a password, and I sent it from remote Raspberry to server in order to make no login access.