To ensure healthy bi-directional connection, Wireguard comes with “persistent keep alive” function for peers to ping the server regularly such that the server can reach the peer sitting behind a firewall. However, problems arise when the server has a dynamic IP, and when the server IP changes the peer does not know to update the old IP by resolving the server domain name again. There needs a way for the peer to monitor the connection and update the resolved server IP as needed (not a built-in function currently in the official Wireguard release). The following Wireguard Connection Monitoring Script can be run as a scheduled cron job in Linux/Ubuntu environment to achieve the desired effect.

The script works by pinging the server’s internal address to determine if the connection is still valid. If the ping fails 3 times, the connection is considered failed and Wiregaurd interface will be restarted.

TLDR: This script automatically forces the peer client to restart so servers with dynamic IP can be updated as appropriate.

PS. For windows client, you can run scheduled batch script to do the same thing.

Usage:

  1. Save the following script as wg-watch.sh (remember to allow execution file permission)
  2. Simply replace the IP address with the Wireguard server’s Internal address
  3. Remember to also adjust the interface wg0 to the one you intend to monitor
  4. Add the script as a cron job (see below for example)

Wireguard Connection Monitoring Script

#!/bin/bash
while [[ $tries -lt 3 ]]
do
    if /bin/ping -c 1 192.168.1.1
    then
        logger -t "wg-watchdog" "wireguard working"
        exit 0
    fi
    tries=$((tries+1))
done
systemctl restart wg-quick@wg0
logger -t "wg-watchdog" "wireguard restarted"

Example of running the script as a cron job

#Add the cron job using the crontab
#Make sure to login as root and set the right file permission, 700 works
crontab -e

#Add the following line and save, example will run the script every hour
#Remember to adjust the file path
0 * * * * /wg-watch.sh >/dev/null 2>&1 | logger -t wg-watchdog-cron

If you like my work, feel free to buy me a coffee:

Leave a Reply