1

I have a raspberry pi with OS 2022-09-22-raspios-bullseye-arm64.img.xz. I have installed a wireguard so that it connects to my own vpn and I have created a service so that as soon as it is turned on it will lift the vpn.

The problem is that on some occasions if the wifi router I'm connected to reboots then the pi loses connection and isn't able to reconnect to the router when it powers up. Manually I have to bring down the wireguard with sudo wg-quick down wg0, at that moment it connects and then I bring up the wireguard interface again

Is there any way to detect that the connection has been lost to stop the wireguard and when it returns it will automatically wake up?

Jaime Roman
  • 113
  • 3

1 Answers1

0

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:

  1. 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.

Seamus
  • 23,558
  • 5
  • 42
  • 83