Keeping your VPN connections robust is essential, especially when using WireGuard tunnels for remote access, site-to-site links, or secure communications. Like many network admins, I’ve faced the frustration of a WireGuard tunnel dropping—often at the least convenient moment. Performing a manual restart on the MikroTik each time is time-consuming and error-prone. This article walks you through a fully automated solution: continuously check the connection from a Linux server and, if needed, remotely restart the MikroTik WireGuard server—using secure workflows and best practices.

Why Automate WireGuard Recovery?#

WireGuard interfaces can go down for many reasons: WAN flaps, ISP hiccups, peer outages, or simply software quirks. You might not notice the downtime until an urgent customer call or failed overnight backup. Automating recovery lets you:

  • Maintain near-zero downtime
  • Reduce human intervention
  • Get back valuable time and peace of mind

The Check-and-Restart Script#

The heart of the setup is a Bash script—let’s call it /usr/local/bin/check_wireguard.sh—that checks tunnel connectivity and triggers a safe remote restart if it’s down. Here’s a generic, anonymized version:

#!/bin/bash

# --- CONFIGURATION ---
PING_TARGET="10.0.100.1"           # Remote IP to check over WireGuard
MIKROTIK_IP="10.0.1.1"             # MikroTik router IP
MIKROTIK_USER="automation"         # Dedicated MikroTik API user
MIKROTIK_PASSWORD="your_secret"    # Strong password!
WIREGUARD_INTERFACE="my-wg-tunnel" # Friendly WG tunnel name (for logs)
LOGGER_NAME="WireGuardMonitor"     # For journal/syslog logging

# --- CHECK TUNNEL ---
if ! ping -c 1 $PING_TARGET &> /dev/null; then
    logger -t $LOGGER_NAME "Ping to $PING_TARGET failed. Restarting WireGuard interface $WIREGUARD_INTERFACE on MikroTik."
    # Restart interface using MikroTik REST API (.id must match actual WG tunnel)
    DISABLE_OUTPUT=$(curl -k -s -u $MIKROTIK_USER:$MIKROTIK_PASSWORD \
        -X POST "http://$MIKROTIK_IP/rest/interface/wireguard/disable" \
        -H "Content-Type: application/json" \
        --data '{".id": "*B"}'
    )
    ENABLE_OUTPUT=$(curl -k -s -u $MIKROTIK_USER:$MIKROTIK_PASSWORD \
        -X POST "http://$MIKROTIK_IP/rest/interface/wireguard/enable" \
        -H "Content-Type: application/json" \
        --data '{".id": "*B"}'
    )
    logger -t $LOGGER_NAME "Disable Output: $DISABLE_OUTPUT"
    logger -t $LOGGER_NAME "Enable Output: $ENABLE_OUTPUT"
    logger -t $LOGGER_NAME "WireGuard interface $WIREGUARD_INTERFACE has been restarted."
else
    logger -t $LOGGER_NAME "Ping to $PING_TARGET successful."
fi

Key points:

  • Pings a remote IP accessible only through the WireGuard tunnel.
  • If unreachable, restarts the MikroTik WireGuard interface using the REST API.
  • Outputs to system logs for audit and troubleshooting.

Securing Your MikroTik Automation User#

  • Create a dedicated user (e.g., automation) in your MikroTik.
  • Give it only the necessary API and WireGuard permissions.
  • Restrict its access in MikroTik’s firewall to only your server’s IP for maximum security.

Never use the main admin account for automation tasks! Minimize your attack surface for peace of mind.

Getting the WireGuard Tunnel ID via the REST API#

To restart a specific WireGuard interface, you need its internal .id (not just its name). Query the IDs using curl:

curl -k -u automation:your_secret \
     -X POST "http://10.0.1.1/rest/interface/wireguard/print" \
     -H "Content-Type: application/json" \
     --data '{".proplist": [".id", "name"]}'

You’ll get output like:

[
  { ".id": "*B", "name": "my-wg-tunnel" },
  { ".id": "*9", "name": "wg-office" }
]

Identify the .id that matches your tunnel’s name. Use this value (e.g., *B) in the disable and enable calls.

Example: Using curl for Authenticated MikroTik API Calls#

Whether querying interfaces or restarting a tunnel, always supply the -u user:password and the JSON content header. For example:

Disable and enable a tunnel:

curl -k -u automation:your_secret \
     -X POST "http://10.0.1.1/rest/interface/wireguard/disable" \
     -H "Content-Type: application/json" \
     --data '{".id": "*B"}'

curl -k -u automation:your_secret \
     -X POST "http://10.0.1.1/rest/interface/wireguard/enable" \
     -H "Content-Type: application/json" \
     --data '{".id": "*B"}'

This ensures authenticated, properly formatted commands every time.

Setting Up systemd to Run the Script Automatically#

Let’s use systemd to schedule this as a timer, running every 5min.

Step 1: Service File#

Create /etc/systemd/system/check_wireguard.service:

[Unit]
Description=Check WireGuard Interface and Restart if Unreachable

[Service]
Type=simple
ExecStart=/usr/local/bin/check_wireguard.sh
StandardOutput=journal
StandardError=journal

Step 2: Timer File#

Create /etc/systemd/system/check_wireguard.timer:

[Unit]
Description=Run Check WireGuard Service every 5 minutes

[Timer]
OnBootSec=5min
OnUnitActiveSec=5min
Unit=check_wireguard.service

[Install]
WantedBy=timers.target

Step 3: Enable and Start#

Reload systemd and activate the timer:

sudo systemctl daemon-reload
sudo systemctl enable --now check_wireguard.timer

Diagnostics#

  • See active timers: systemctl list-timers --all | grep check_wireguard
  • Review logs: journalctl -t WireGuardMonitor

Real-World Benefits and Lessons Learned#

After deploying this solution in my own network, random outages (and the stress of manual monitoring) disappeared. No more urgent remote calls late at night! My WireGuard tunnels now auto-heal, backed by secure, auditable automation.

Remember:

  • Limit API user rights and IP access on MikroTik for safety.
  • Test all commands manually before relying on automation.
  • Monitor logs to tune false positives/negatives (for example, avoid restarts from transient ping loss).

Conclusion#

Automating WireGuard tunnel checks and recovery with a simple Linux script and systemd is straightforward, reliable, and a major quality-of-life upgrade for anyone managing MikroTik routers. Secure your API, set-and-forget your scheduled checks, and let your VPN connections stay resilient—whatever the internet throws at you.