Automatic WireGuard initalization after boot-up using Monit

Started by Monju0525, June 19, 2026, 06:00:45 PM

Previous topic - Next topic
Had problems connecting to wg0 interface that required re-starting wg0, so I am sharing my monit implementation.
It is equivalent to re-starting/toggling the dashboard's WG.
Monit needs to start first (3 to 4 minutes) before Monit re-starts WG.

Tested under OpnSense 26.1.10


Monit Implementation
Steps
#1 Set Opnsense Monit Service setings and Service tests settings
#2 Add wg0_monit_start.sh
#3 Service -> Monit -> Status


#1
Opnsense Services Monit
Service Settings
Name: wg0_monit_start
Type: custom
Path: /usr/local/bin/bash  /usr/local/opnsense/scripts/wireguard/wg0_monit_start.sh
Start: /bin/sh -c '/usr/local/sbin/pluginctl -s wireguard restart'
Tests: ZeroStatus

Service Tests Settings
Name: ZeroStatus
Condition: status == 0
Action: Start

#2
nano /usr/local/opnsense/scripts/wireguard/wg0_monit_start.sh
======
#!/bin/bash

# RC is the connection state which defaults = 1
RC=1

# Test wg0 connection state and if no packets are received it needs to be restarted with RC=0
# RC=0 uses the ZeroStatus test to re-start wg0

[[ $(netstat -i | grep -F -- "          0    - " | \
grep "VPN Instance Tunnel IP address"  | wc -l) -eq "1" ]] &&  RC=0 && echo !connected  && exit $RC \
|| echo connected && exit 1
======

chmod + /usr/local/opnsense/scripts/wireguard/wg0_monit_start.sh



#3
Program 'wg0_monit_start'
  status                      OK
  monitoring status            Monitored
  monitoring mode              active
  on reboot                    start
  last exit value              1
  last output                  connected
  data collected              Fri, 19 Jun 2026 11:49:02


====


Updated the script with an alternatuve method
====
#!/bin/bash
#Alternative
shopt -s extglob

# Test the wg0 connection state using monit ZeroStatus test
# RC =1 is the connection state which defaults the wg0 as being connected -> exit 1
# reports as 'status =1'

RC=1

# If no wg0 packets are received, it needs to be restarted with RC =0 -> exit 0
# Important: need to report 'status =0' to the opnsense monit ZeroStatus test
# which will re-start the wg0 connection

# in-line command
#[[ $(netstat -i | grep -F -- "          0     - " | grep "100.80.224.94"  | wc -l) -eq "1" ]] \
#&& RC=0 && echo "!connected"   $(date +"%Y-%m-%d %H:%M:%S") && exit $RC \
#|| echo "connected"  $(date +"%Y-%m-%d %H:%M:%S") && exit $RC


RC=`netstat -i | grep -F -- "          0     - " | grep "100.80.224.94" | wc -l`
#echo $RC
[$RC -eq  1 ] && RC="0" || RC="1"

case $RC in
0) printf "wg0 !connected  $(date +"%Y-%m-%d %H:%M:%S") \n" && exit 0;;
1) printf "wg0  connected  $(date +"%Y-%m-%d %H:%M:%S") \n" && exit 1;;
*) printf "Issue with wg0_monit_start.sh \n";;
esac



====