Last active
March 14, 2025 09:51
-
-
Save mehstg/466045bbd0316d7be0a196c1a049477e to your computer and use it in GitHub Desktop.
Wireguard CLI to MQTT Bash Script - For getting Wireguard information in to Home Assistant MQTT sensors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A script to pull information from the Wireguard CLI and redirect to a MQTT Broker | |
# Based on the original script written by valvex - https://community.home-assistant.io/t/send-wireguard-client-info-to-ha-with-mqtt-template-sensor-to-show-active-clients/259532 | |
# Paul Braham 2022 | |
#!/bin/bash | |
CONF_FILE="/etc/wireguard/wg0.conf" | |
MQTT_IP="192.168.1.200" | |
MQTT_USERNAME="mqttuser" | |
MQTT_PASSWORD="mqttpass" | |
while IFS= read -r RESULT | |
do | |
IP=$(sudo wg | grep -A 4 $RESULT | grep 'endpoint' | sed s'/endpoint://' | sed -e 's/^[[:space:]]*//') | |
LASTSEEN=$(sudo wg | grep -A 4 $RESULT | grep 'latest' | sed s'/latest handshake://' | sed -e 's/^[[:space:]]*//') | |
DATA=$(sudo wg | grep -A 4 $RESULT | grep 'transfer' | sed s'/transfer://' | sed -e 's/^[[:space:]]*//') | |
PEER_ID_CLEAN=$(echo $RESULT | tr -d '+#/=,') | |
FINAL='{"Client":"'"$PEER_ID_CLEAN"'","IP":"'"$IP"'","Last Seen":"'"$LASTSEEN"'","Data":"'"$DATA"'"}' | |
mosquitto_pub -h $MQTT_IP -u $MQTT_USERNAME -P $MQTT_PASSWORD -t "wireguard/$PEER_ID_CLEAN" -m "$FINAL" -r | |
done < <(sudo wg | grep peer: | cut -d" " -f2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment