Cleaned up #2.
nano /usr/local/opnsense/scripts/wireguard/wg0_monit_start.sh
#!/bin/bash
# Test the wg0 connection state and if no packets are received ( a match )
# then wg0 needs to be restarted with exit 0
# which uses ZeroStatus test to re-start wg0
#==
# pulls vpn end-tunnel address from ifconfig wg0
ip_addr=$(ifconfig wg0 | awk '/inet / {print $2}')
read -ra fields <<< "$(netstat -i | grep -E '\swg0\s')"
#echo "rx_packets= ${fields[4]}"
# Test wg0 column 5 or fields[4]
# add echo protection 070726
[[ -n "${fields[4]}" && "${fields[4]}" -eq 0 ]] \
&& { echo "_wg0 !connected $(date +"%Y-%m-%d %H:%M:%S")"; exit 0; } \
|| { echo "_wg0 connected to $ip_addr $(date +"%Y-%m-%d %H:%M:%S")"; exit 1; }
#==
# equals a '0' -> match -> exit 0 -> re-starts wg0
# not equal condition -> no match -> do not restart wg0
# Verification
# netstat -i | grep wg0
# wg0 1420 <Link#9> wg0 0 0 0 4528 0 0
# wg0 - xxx.xxx.xxx.xxx/32 xxx.xxx.xxx.xxx 0 - - -
Program 'wg0_monit_start'
status OK
monitoring status Monitored
monitoring mode active
on reboot start
last exit value 1
last output _wg0 connected to xxx.xxx.xxx.xxx 2026-07-09 07:55:54
data collected Thu, 09 Jul 2026 07:57:54
nano /usr/local/opnsense/scripts/wireguard/wg0_monit_start.sh
#!/bin/bash
# Test the wg0 connection state and if no packets are received ( a match )
# then wg0 needs to be restarted with exit 0
# which uses ZeroStatus test to re-start wg0
#==
# pulls vpn end-tunnel address from ifconfig wg0
ip_addr=$(ifconfig wg0 | awk '/inet / {print $2}')
read -ra fields <<< "$(netstat -i | grep -E '\swg0\s')"
#echo "rx_packets= ${fields[4]}"
# Test wg0 column 5 or fields[4]
# add echo protection 070726
[[ -n "${fields[4]}" && "${fields[4]}" -eq 0 ]] \
&& { echo "_wg0 !connected $(date +"%Y-%m-%d %H:%M:%S")"; exit 0; } \
|| { echo "_wg0 connected to $ip_addr $(date +"%Y-%m-%d %H:%M:%S")"; exit 1; }
#==
# equals a '0' -> match -> exit 0 -> re-starts wg0
# not equal condition -> no match -> do not restart wg0
# Verification
# netstat -i | grep wg0
# wg0 1420 <Link#9> wg0 0 0 0 4528 0 0
# wg0 - xxx.xxx.xxx.xxx/32 xxx.xxx.xxx.xxx 0 - - -
Program 'wg0_monit_start'
status OK
monitoring status Monitored
monitoring mode active
on reboot start
last exit value 1
last output _wg0 connected to xxx.xxx.xxx.xxx 2026-07-09 07:55:54
data collected Thu, 09 Jul 2026 07:57:54
"