Skip to content

Instantly share code, notes, and snippets.

@rhysrhaven
Last active October 25, 2018 14:05
Show Gist options
  • Save rhysrhaven/5347433 to your computer and use it in GitHub Desktop.
Save rhysrhaven/5347433 to your computer and use it in GitHub Desktop.
Returns records from DNS servers. Built to be used as an external check from Zabbix.
#!/bin/bash
#
# DNS Check Script
# Given two parameters, the DNS record type and a domainname
# Will return the record if exists, 'NXDOMAIN' if it doesnt.
#
DIG='/usr/bin/dig'
VALID_RECORDS=(
'mx'
'a'
'aaaa'
'cname'
'ns'
'ptr'
'soa'
'spf'
'srv'
'txt'
)
# Checks to see if arg1 is in array arg2
# first line lets us pass a reference to a variable to this function
function containsItem() {
eval maharray=\$\{${2}[@]\}
case "${maharray}" in *"${1}"*) return 0 ;; esac
return 1
}
# pulled from here: http://www.linuxjournal.com/content/validating-ip-address-bash-script
function valid_ip() {
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
# exit with error if no name passed
if [ -z "${2}" ]; then
exit 5
fi
# Exit if not valid record
RR_RECORD="$(echo ${1} | awk '{print tolower($0)}')"
if ! $(containsItem $RR_RECORD VALID_RECORDS); then
echo "Please pass valid resource record"
exit 1
fi
# See if user passed specific DNS Server for us to try
if valid_ip ${3}; then
RESULT="$($DIG +short @${3} ${1} ${2})"
else
RESULT="$($DIG +short ${1} ${2})"
fi
# Return the output of our DNS query
if [ -z "${RESULT}" ]; then
echo 'NXDOMAIN'
exit 0
else
echo "${RESULT}" | sort -n
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment