17
Дек

Отслеживаем клиентов wireguard с уведомлением в Telegram

Задача отслеживать подключаемых и отключаемых wireguard клиентов на сервере и слать telegram уведомления в бота
#!/usr/bin/env bash

WG_IF="wg0"
CLIENTS_DIR="/etc/wireguard/clients"
STATE_FILE="/tmp/wg_state"
TIMEOUT=180

declare -A IP_TO_NAME
declare -A PUBKEY_TO_IP
declare -A OLD
declare -A NEW

# --- загружаем прошлое состояние ---
[[ -f "$STATE_FILE" ]] && source "$STATE_FILE"

# --- IP -> имя клиента ---
for f in "$CLIENTS_DIR"/*.conf; do
    name=$(basename "$f" .conf)
    ip=$(grep -E '^Address' "$f" | cut -d= -f2 | tr -d ' ' | cut -d/ -f1)
    [[ -n "$ip" ]] && IP_TO_NAME["$ip"]="$name"
done

# --- pubkey -> IP ---
while read -r pubkey ips; do
    ip="${ips%%/*}"
    PUBKEY_TO_IP["$pubkey"]="$ip"
done < <(wg show "$WG_IF" allowed-ips)

NOW=$(date +%s)

# --- текущие подключения ---
while read -r pubkey handshake; do
    [[ "$handshake" -eq 0 ]] && continue
    (( NOW - handshake > TIMEOUT )) && continue

    NEW["$pubkey"]=1

    if [[ -z "${OLD[$pubkey]}" ]]; then
        ip="${PUBKEY_TO_IP[$pubkey]}"
        name="${IP_TO_NAME[$ip]:-unknown}"

        telegram-send "🟢 WireGuard CONNECT
Client: $name
IP: $ip"
    fi
done < <(wg show "$WG_IF" latest-handshakes)

# --- отключения ---
for pubkey in "${!OLD[@]}"; do
    if [[ -z "${NEW[$pubkey]}" ]]; then
        ip="${PUBKEY_TO_IP[$pubkey]}"
        name="${IP_TO_NAME[$ip]:-unknown}"

        telegram-send "🔴 WireGuard DISCONNECT
Client: $name
IP: $ip"
    fi
done

# --- сохраняем состояние ---
{
    echo "declare -A OLD=("
    for k in "${!NEW[@]}"; do
        echo "  [$k]=1"
    done
    echo ")"
} > "$STATE_FILE"
Делаем исполняемым
chmod +x /root/wg_notify.sh
и ставим в cron
*/1 * * * * /root/wg_notify.sh

Обратная связь

    The average number of adverse effects was 3. T max is 23 minutes in females and 32 minutes in males. What other drugs will affect doxercalciferol Viagra natural sin receta. Archived from the original on 2009-08-14.

    Talk to your doctor before using this form of cefadroxil if you have diabetes. What should I tell my healthcare team before starting CABLIVI? There is no FDA guidance on the use of Tetracycline (oral) with respect to specific gender populations https://www.apotheke-rezeptfreie.com/. Opper K, Uder S, Song K Development of Heterogeneous and Homogeneous Platforms for Rapid Analysis of DNA-Protein Interactions.

    Contact Us