check_dns.sh 949 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/bin/sh
  2. while getopts "H:s:" opt; do
  3. case "$opt" in
  4. H) HOST="$OPTARG" ;;
  5. s) SERVER="$OPTARG" ;;
  6. *) echo "Usage: $0 -H host -s server"; exit 3 ;;
  7. esac
  8. done
  9. if [ -z "$SERVER" ]; then
  10. echo "No DNS Server provided"
  11. exit 3
  12. fi
  13. if [ -z "$HOST" ]; then
  14. echo "No host to test provided"
  15. exit 3
  16. fi
  17. # run dig and measure the time it takes to run
  18. START_TIME=$(date +%s%3N)
  19. dig_output=$(dig +short +timeout=2 +tries=1 "$HOST" @"$SERVER" 2>/dev/null)
  20. dig_rc=$?
  21. dig_output_ips=$(echo "$dig_output" | grep -E '^[0-9.]+$' | sort | paste -sd ',' -)
  22. END_TIME=$(date +%s%3N)
  23. ELAPSED_TIME=$((END_TIME - START_TIME))
  24. # validate and perform nagios like output and exit codes
  25. if [ $dig_rc -ne 0 ] || [ -z "$dig_output" ]; then
  26. echo "Domain $HOST was not found by the server"
  27. exit 2
  28. elif [ $dig_rc -eq 0 ]; then
  29. echo "DNS OK: $ELAPSED_TIME ms response time. $HOST returns $dig_output_ips"
  30. exit 0
  31. else
  32. echo "Unknown error"
  33. exit 3
  34. fi