The Problem: I have some home automation stuff (Z-wave switches and EtherRain sprinkler controller) running and I want to be able to leave the house. I do not want to open any ports on my router or worry about setting up some kind of dynamic dns. I am lazy.
My Solution: (or at least this wave of it) I have a remote server that is always serving webpages. I want my Pi to check in with that server to see if it should open itself up to the world using ssh reverse port forwarding.
What I did:
1. I created a user on my ‘always on’ web server for the ssh tunnel and I setup key authentication from my Raspberry Pi.
2. I created a file on the ‘always on’ web server that I called ‘openpi.php’ and put the file into a directory that serves the web pages. The file has a single line with ‘no’ in it.
3. On my Pi, I created a bash script that downloads the latest copy of the ‘openpi.php’ page and checks to see if it contains ‘yes’. If it contains ‘yes’, a tunnel is opened and remote viewing of the Pi is allowed through the always on web server.
Here is what the script currently looks like:
#!/bin/bash
WGET="/usr/bin/wget"
$WGET -q --tries=10 --timeout=5 http://youralwaysonserver/openpi.php -O /tmp/openpi &> /dev/null
if grep -Fxq "yes" /tmp/openpi
then
ssh -gNnT -R *:55555:raspberrypi.local:80 [email protected] &
PID=$!
echo "Opened"
sleep 180s;
kill $PID
echo "Closed"
else
echo "no"
fi
I am working on keeping the tunnel open for only 180 seconds but you could change this to whatever time setting you want.
4. On my Pi, I setup a cron job to run the script every 10 minutes. You can set this to whatever frequency works best for you.
> crontab -e
then add
*/10 * * * * /home/pi/remote_manage
and save.
And that is it. Now when I leave the house, if I need access, I log in to my web server and change ‘no’ to ‘yes’ in ‘openpi.php’.