Replace IPs in stdin with their DNS names
June 12, 2015 —
Rob Hutten
This script takes standard input and replaces any occurance of an IP address with its name as per a DNS lookup.
#!/bin/bash
#
# Rob Hutten, 2015
# http://hutten.org/rob/scripts
# Reads from stdin; replaces IP addresses with their names
# as found in the DNS.
PATH=/bin:/usr/bin
sedscript=$(mktemp /tmp/poot.XXXXX)
input=$(mktemp /tmp/toot.XXXXX)
cat > $input
ips=($(tr ' ,:' '\012\012\012' < $input \
| egrep '^[0-9\.][0-9\.]*$' \
| egrep '[0-9]' \
| egrep '\.' \
| sort | uniq))
cat > $sedscript << EOF
#!/usr/bin/sed -f
EOF
for ip in ${ips[@]} ; do
dns=$(host $ip | rev | awk '{print $1}' | rev | cut -d\. -f1)
if [[ $dns =~ SERVFAIL ]] ; then
dns=$ip
fi
echo s/${ip}/${dns}/g >> $sedscript
done
chmod +x $sedscript
$sedscript < $input
rm -f $sedscript $input