wireguard-monitor: Initial commit

Signed-off-by: Milan Pandurov <milanpandurov@pm.me>
This commit is contained in:
2025-02-18 13:26:28 +01:00
commit 958c2c3cbd
4 changed files with 84 additions and 0 deletions

View File

@@ -0,0 +1,10 @@
## Wireguard Monitor
Shell script and systemd service that will monitor if wireguard link is active. In case it fails wireguard connection will be restarted.
### Installation
To install simply run:
```
sudo ./install.sh
```

11
wireguard-monitor/install.sh Executable file
View File

@@ -0,0 +1,11 @@
#!/bin/bash
set -e
cp wireguard-reconnect /usr/bin/wireguard-reconnect
cp wireguard-monitor.service /etc/systemd/system/wireguard-monitor.service
systemctl daemon-reload
systemctl enable wireguard-monitor.service
systemctl start wireguard-monitor.service
echo "Installed wireguard monitoring service"

View File

@@ -0,0 +1,18 @@
[Unit]
Description=Wireguard Monitoring Service
After=wg-quick@home.service
[Service]
Type=simple
ExecStart=/usr/bin/wireguard-reconnect
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
# User and group the service will run as (change as needed)
User=root
Group=root
[Install]
WantedBy=multi-user.target

View File

@@ -0,0 +1,45 @@
#!/bin/bash
GATEWAY_IP="192.168.5.1"
PING_DELAY_S=30
RECONNECT_ATTEMPTS=10
RECONNECT_DELAY=60
WG_INTERFACE="home"
REBOOT_AFTER_FAILED_ATTEMPTS=true
FAILED_ATTEMPTS=0
while : ; do
if ! wg show "$WG_INTERFACE" > /dev/null; then
echo "INFO: WG interface $WG_INTERFACE is not active, not doing anything"
sleep "$PING_DELAY_S"
continue
fi
if ! ping -c 1 "$GATEWAY_IP" > /dev/null; then
echo "ERROR: Failed to ping the gateway ($GATEWAY_IP). Restarting interface $WG_INTERFACE"
wg-quick down "$WG_INTERFACE"
echo "INFO: Stopped WG interface $WG_INTERFACE"
sleep "$RECONNECT_DELAY"
if ! wg-quick up "$WG_INTERFACE"; then
echo "WARNING: Failed starting the interface..."
else
echo "INFO: Started WG interface $WG_INTERFACE"
fi
FAILED_ATTEMPTS=$(( FAILED_ATTEMPTS + 1))
if (( FAILED_ATTEMPTS > RECONNECT_ATTEMPTS )); then
echo "Failed $FAILED_ATTEMPTS times to recover connection..."
if $REBOOT_AFTER_FAILED_ATTEMPTS; then
echo "Rebooting..."
reboot
else
echo "Will continue trying..."
FAILED_ATTEMPTS=$(( 0 ))
fi
fi
fi
sleep "$PING_DELAY_S"
done