You should be able to accomplish that with a simple shell script that you run every 5-10 minutes from a cron job. In fact, a quick search turned up this repo on GitHub that does exactly that!
There are a couple of minor changes I'd suggest for using this on your RPi:
- The author's install script is broken, so just copy and paste the following simple script in your editor, then save the file to
/usr/local/sbin/wg-check.sh (instead of /opt):
#!/bin/bash
ping -c1 [edit it to your peer ip] > /dev/null
if [ $? -eq 0 ]
then
exit 0
else
wg-quick down wg0;
wg-quick up wg0;
fi
Save the file to /usr/local/sbin/wg-check.sh, and then make it executable:
$ sudo chmod 755 /usr/local/sbin/wg-check.sh
The author's cron job isn't great, so use this instead:
$ sudo crontab -e
in your editor, add the following line, then save & exit the editor:
/5 * * * /usr/local/sbin/wg-check.sh >> /home/pi/wg_log.txt 2>&1
What's happening:
*/5 runs the script at /usr/local/sbin/wg-check.sh once every 5 minutes - you can adjust the frequency as necessary. (Alternatively, you can run script from the command line as required.)
>> re-directs any output (stdout) from the script to a log file at /home/pi/wg_log.txt; change the filename/location to suit yourself.
2>&1 re-directs any errors (stderr) from the script to the log file
The log file is entirely optional of course, but I'd reccomend you consider, at least initially, until you're comfortable this is doing what it should.