Skip to content

Instantly share code, notes, and snippets.

@schappim
Created December 10, 2024 04:01
Show Gist options
  • Save schappim/1b274db0cd5c8975a317917a812a0eb8 to your computer and use it in GitHub Desktop.
Save schappim/1b274db0cd5c8975a317917a812a0eb8 to your computer and use it in GitHub Desktop.
Pi-hole Query Log Analyzer
#!/bin/bash
DEFAULT_PIHOLE_IP="localhost"
DEFAULT_LIMIT=10
show_help() {
echo "Usage: $0 [-i ip_address] [-t token] [-n number] [-c client] [-d domain]"
echo " -i: IP address of Pi-hole server (default: localhost)"
echo " -t: API token (required)"
echo " -n: Number of queries to show (default: 10)"
echo " -c: Filter by client IP"
echo " -d: Filter by domain"
echo " -h: Show this help message"
exit 1
}
while getopts "i:t:n:c:d:h" opt; do
case $opt in
i) PIHOLE_IP="$OPTARG";;
t) API_TOKEN="$OPTARG";;
n) LIMIT="$OPTARG";;
c) CLIENT="$OPTARG";;
d) DOMAIN="$OPTARG";;
h) show_help;;
?) show_help;;
esac
done
if [ -z "$API_TOKEN" ]; then
echo "Error: API token is required"
show_help
fi
PIHOLE_IP=${PIHOLE_IP:-$DEFAULT_PIHOLE_IP}
LIMIT=${LIMIT:-$DEFAULT_LIMIT}
# Build query string based on filters
QUERY="http://${PIHOLE_IP}/admin/api.php?getAllQueries&auth=${API_TOKEN}"
if [ ! -z "$CLIENT" ]; then
QUERY="${QUERY}&client=${CLIENT}"
fi
if [ ! -z "$DOMAIN" ]; then
QUERY="${QUERY}&domain=${DOMAIN}"
fi
QUERY="${QUERY}&number=${LIMIT}"
# Fetch and display queries
echo "Recent Queries:"
echo "--------------"
response=$(curl -s "$QUERY")
echo "$response" | jq -r '.data[] | "\(.timestamp) | \(.domain) | \(.client) | \(if .blocked == "1" then "BLOCKED" else "ALLOWED" end)"' | \
awk -F'|' '{printf "Time: %s\nDomain: %s\nClient: %s\nStatus: %s\n\n", $1, $2, $3, $4}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment