Automate WireGuard client management with scripts for provisioning and configuration

Intermediate 45 min Apr 03, 2026 1,227 views
Ubuntu 24.04 Debian 12 AlmaLinux 9 Rocky Linux 9

Create automated scripts to provision WireGuard clients, manage configurations, and monitor VPN connections. This tutorial builds comprehensive management tools for production WireGuard deployments.

Prerequisites

  • WireGuard server already installed and configured
  • Root or sudo access
  • Basic knowledge of WireGuard configuration
  • Understanding of JSON and bash scripting

What this solves

Managing WireGuard clients manually becomes cumbersome as your VPN infrastructure grows. This tutorial creates automated scripts for client provisioning, configuration management, and monitoring to streamline WireGuard operations. You'll build tools that generate client configurations, distribute keys securely, and track connection health automatically.

Step-by-step configuration

Verify WireGuard server installation

Ensure your WireGuard server is properly configured before setting up automation scripts. This confirms the base infrastructure is working correctly.

sudo systemctl status wg-quick@wg0
sudo wg show
Note: If WireGuard isn't installed, follow our WireGuard server setup guide first.

Install required dependencies

Install tools needed for automated client management including QR code generation and JSON processing utilities.

sudo apt update
sudo apt install -y qrencode jq curl wireguard-tools
sudo dnf install -y epel-release
sudo dnf install -y qrencode jq curl wireguard-tools

Create management directory structure

Set up organized directories for scripts, client configurations, and logs with proper permissions.

sudo mkdir -p /opt/wireguard-manager/{scripts,clients,logs,templates}
sudo mkdir -p /opt/wireguard-manager/clients/{active,revoked,configs}
sudo chown -R root:root /opt/wireguard-manager
sudo chmod -R 755 /opt/wireguard-manager
sudo chmod 700 /opt/wireguard-manager/clients

Create client database file

Initialize a JSON database to track client information, IP assignments, and connection status.

{
  "clients": [],
  "next_ip": 2,
  "subnet": "10.0.0.0/24",
  "server_public_key": "",
  "server_endpoint": "",
  "dns_servers": ["1.1.1.1", "8.8.8.8"]
}
sudo chmod 600 /opt/wireguard-manager/clients/database.json

Create client configuration template

Define a reusable template for generating client configurations with proper security settings.

[Interface]
PrivateKey = CLIENT_PRIVATE_KEY
Address = CLIENT_IP/32
DNS = DNS_SERVERS

[Peer]
PublicKey = SERVER_PUBLIC_KEY
AllowedIPs = 0.0.0.0/0
Endpoint = SERVER_ENDPOINT
PersistentKeepalive = 25

Create client provisioning script

Build the main script that provisions new clients, generates keys, and updates server configuration automatically.

#!/bin/bash

# WireGuard Client Provisioning Script
# Usage: ./provision-client.sh 

set -euo pipefail

# Configuration
WG_DIR="/opt/wireguard-manager"
CLIENT_DB="$WG_DIR/clients/database.json"
SERVER_CONFIG="/etc/wireguard/wg0.conf"
TEMPLATE="$WG_DIR/templates/client.conf"
LOG_FILE="$WG_DIR/logs/provisioning.log"

# Logging function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# Validate input
if [[ $# -lt 1 ]]; then
    echo "Usage: $0 
sudo chmod 755 /opt/wireguard-manager/scripts/provision-client.sh

Create client revocation script

Build a script to safely revoke client access by removing their configuration and updating the server.

#!/bin/bash

# WireGuard Client Revocation Script
# Usage: ./revoke-client.sh 

set -euo pipefail

# Configuration
WG_DIR="/opt/wireguard-manager"
CLIENT_DB="$WG_DIR/clients/database.json"
SERVER_CONFIG="/etc/wireguard/wg0.conf"
LOG_FILE="$WG_DIR/logs/provisioning.log"

# Logging function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# Validate input
if [[ $# -ne 1 ]]; then
    echo "Usage: $0 
sudo chmod 755 /opt/wireguard-manager/scripts/revoke-client.sh

Create client monitoring script

Build a monitoring script that checks client connection status and updates the database with connection information.

#!/bin/bash

# WireGuard Client Monitoring Script
# Updates client connection status and last seen timestamps

set -euo pipefail

# Configuration
WG_DIR="/opt/wireguard-manager"
CLIENT_DB="$WG_DIR/clients/database.json"
LOG_FILE="$WG_DIR/logs/monitoring.log"
STATS_FILE="$WG_DIR/logs/connection-stats.json"

# Logging function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# Get current WireGuard status
WG_STATUS=$(sudo wg show wg0 dump 2>/dev/null || echo "")

if [[ -z "$WG_STATUS" ]]; then
    log "WARNING: Cannot retrieve WireGuard status"
    exit 1
fi

# Initialize stats
STATS=$(cat <
sudo chmod 755 /opt/wireguard-manager/scripts/monitor-clients.sh

Create client listing script

Build a utility script to display client information in a readable format for administrative purposes.

#!/bin/bash

# WireGuard Client Listing Script
# Displays client information in various formats

set -euo pipefail

# Configuration
WG_DIR="/opt/wireguard-manager"
CLIENT_DB="$WG_DIR/clients/database.json"

# Parse arguments
SHOW_ALL=false
SHOW_ACTIVE=false
SHOW_REVOKED=false
OUTPUT_FORMAT="table"

while [[ $# -gt 0 ]]; do
    case $1 in
        --all)
            SHOW_ALL=true
            shift
            ;;
        --active)
            SHOW_ACTIVE=true
            shift
            ;;
        --revoked)
            SHOW_REVOKED=true
            shift
            ;;
        --json)
            OUTPUT_FORMAT="json"
            shift
            ;;
        --help)
            echo "Usage: $0 [--all|--active|--revoked] [--json]"
            echo "  --all      Show all clients (default)"
            echo "  --active   Show only active clients"
            echo "  --revoked  Show only revoked clients"
            echo "  --json     Output in JSON format"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Default to show all if no filter specified
if [[ "$SHOW_ACTIVE" == "false" && "$SHOW_REVOKED" == "false" ]]; then
    SHOW_ALL=true
fi

# Build jq filter
JQ_FILTER=".clients[]"
if [[ "$SHOW_ACTIVE" == "true" ]]; then
    JQ_FILTER="$JQ_FILTER | select(.status == \"active\")"
elif [[ "$SHOW_REVOKED" == "true" ]]; then
    JQ_FILTER="$JQ_FILTER | select(.status == \"revoked\")"
fi

if [[ "$OUTPUT_FORMAT" == "json" ]]; then
    jq "[$JQ_FILTER]" "$CLIENT_DB"
else
    echo "WireGuard Client Status Report"
    echo "Generated: $(date)"
    echo ""
    
    printf "%-20s %-15s %-12s %-20s %-20s\n" "Name" "IP Address" "Status" "Created" "Last Seen"
    printf "%-20s %-15s %-12s %-20s %-20s\n" "----" "----------" "------" "-------" "---------"
    
    while IFS= read -r client; do
        if [[ "$client" == "null" ]]; then
            continue
        fi
        
        NAME=$(echo "$client" | jq -r '.name')
        IP=$(echo "$client" | jq -r '.ip')
        STATUS=$(echo "$client" | jq -r '.status')
        CREATED=$(echo "$client" | jq -r '.created' | cut -d'T' -f1)
        LAST_SEEN=$(echo "$client" | jq -r '.last_seen // "Never"' | cut -d'T' -f1)
        
        printf "%-20s %-15s %-12s %-20s %-20s\n" "$NAME" "$IP" "$STATUS" "$CREATED" "$LAST_SEEN"
    done < <(jq -c "$JQ_FILTER" "$CLIENT_DB")
fi
sudo chmod 755 /opt/wireguard-manager/scripts/list-clients.sh

Set up automated monitoring with cron

Configure cron to run client monitoring automatically and rotate logs to maintain system health.

sudo crontab -e

Add these lines to run monitoring every 5 minutes and daily log rotation:

# WireGuard client monitoring
*/5 * * * * /opt/wireguard-manager/scripts/monitor-clients.sh

# Daily log rotation
0 0 * * * find /opt/wireguard-manager/logs -name "*.log" -mtime +30 -delete

Create management wrapper script

Build a main management script that provides a unified interface for all WireGuard client operations.

#!/bin/bash

# WireGuard Manager - Unified client management interface

set -euo pipefail

SCRIPT_DIR="/opt/wireguard-manager/scripts"

show_help() {
    cat << EOF
WireGuard Manager - Client Management Tool

Usage: wg-manager 
sudo chmod 755 /opt/wireguard-manager/wg-manager
sudo ln -sf /opt/wireguard-manager/wg-manager /usr/local/bin/wg-manager

Initialize the management system

Set up the initial configuration with your server details and run the first monitoring check.

# Update database with server information
sudo jq --arg endpoint "vpn.example.com:51820" \
        --arg dns "1.1.1.1,8.8.8.8" \
        '.server_endpoint = $endpoint | .dns_servers = ($dns | split(","))' \
        /opt/wireguard-manager/clients/database.json > /tmp/db.json

sudo mv /tmp/db.json /opt/wireguard-manager/clients/database.json

# Run initial monitoring
sudo /opt/wireguard-manager/scripts/monitor-clients.sh

Automated install script

Run this to automate the entire setup

Sie möchten das nicht selbst verwalten?

Wir betreiben Infrastruktur für Unternehmen, die auf Verfügbarkeit angewiesen sind. Vollständig verwaltet, mit einem festen Ansprechpartner, der Ihre Umgebung kennt.

Sie erhalten einen festen Ansprechpartner, der Ihr Setup kennt

Am Schreibtisch in Rotterdam 14:54 · erreichbar per Nachricht, kein Ticketformular