Skip to content

Instantly share code, notes, and snippets.

@mehstg
Last active March 14, 2025 09:51
Show Gist options
  • Save mehstg/466045bbd0316d7be0a196c1a049477e to your computer and use it in GitHub Desktop.
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
# 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