Gather MX Records for a List of Domains
This is a simple one: get a list of MX records for the given domains and output into CSV file. Really, the only interesting part of this is the use of array to temporarily store output of the dig
command. The array is later used to prepend the correct number of column headers to the CSV file. This can be particularly useful of the output is used to generate a database table.
#!/bin/bash infile="/tmp/domainlist.txt" outfile="/tmp/domainlist_mx.csv" IFS=$'\n'; a=($(for d in `grep -v ^# "${infile}" | grep .`; do mx="$(timeout 10 dig ${d} MX 2>/dev/null | \ grep "^${d}.*MX" | awk '{print $NF}' | sort -u | sed 's/\.$//g')"; if [ ! -z "${mx}" ]; then echo ${d} ${mx} | \ sed 's/ /,/g'; else echo ${d}; fi; done)); unset IFS printf '%s\n' ${a[@]} | printf '%s\n' ${a[@]} | (echo "DOMAIN,$(for i in $(seq 1 $(printf '%s\n' ${a[@]} | \ awk -F, '{if (NF > max) {max = NF}} END{print max}')); do echo -n "MX_RECORD_${i},"; done | sed 's/,$//g')" && cat) | \ tee "${outfile}"