Skip to content

Instantly share code, notes, and snippets.

@gfoss
Last active April 2, 2024 11:06
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gfoss/4453950 to your computer and use it in GitHub Desktop.
Save gfoss/4453950 to your computer and use it in GitHub Desktop.
Basic nslookup loops for Windows and Linux
*****WINDOWS*****
//nslookup - subnet range
c:\>for /L %i in (1,1,255) do @nslookup 10.10.10.%i [server to resolve from] 2>nul | find "Name" && echo 10.10.10.%i && @echo [ctrl+g]
//nslookup - file of ip's
NAME c:\>for /F %i in ([file.txt]) do @nslookup %i [server to resolve from] 2>nul | find "Name" && echo %i
ADDRESS c:\>for /F %i in ([file.txt]) do @nslookup %i [server to resolve from] 2>nul | find "Address" && echo %i
Or just run c:\>nslookup and paste in the list
This does not have as clean of output as the for loop though
********************
*****LINUX*****
#script
#!/bin/sh
for IP in `cat ./ips.txt`
do
printf "$IP\t"
LOOKUP_RES=`nslookup $IP`
FAIL_COUNT=`echo $LOOKUP_RES | grep "** server can't find " | wc -l`;
if [ $FAIL_COUNT -eq 1 ]
then
NAME='Bad FQDNS\n';
else
NAME=`echo $LOOKUP_RES | grep -v nameserver | cut -f 2 | grep name | cut -f 2 -d "=" | sed 's/ //'`;
fi
echo $NAME
done
# one-liner
$ for i in `cat urls.txt`; do nslookup $i 2>/dev/null | grep Address | tail -n 1 | cut -d " " -f 3; done > ips.txt
********************
@daretogo
Copy link

daretogo commented Jan 27, 2022

So if you want to go the other way - you have DNS names but you want IPs, I worked off yours and came up with:

#script
#!/bin/sh
for DNAME in `cat urls.txt`
do
  printf "$DNAME "
	LOOKUP_RES=`nslookup $DNAME`

	FAIL_COUNT=`echo $LOOKUP_RES | grep "Can't find" | wc -l`;

	if [ $FAIL_COUNT -eq 1 ]
	then
		NAME='Not in DNS';
	else
		NAME=`echo $LOOKUP_RES | grep Address: | tail -1 | cut -c 9-30`;
	fi
	echo $NAME
done

Technically I only tested it on Mac, but should work the same on linux/bash.

@gfoss
Copy link
Author

gfoss commented Jan 31, 2022

nice! Been a while since I've looked at this gist, but glad to see it's still useful. :-)

@badabing2005
Copy link

@daretogo
You should put the $LOOKUP_RES in double quotes, otherwise line breaks will not be kept and everything will end up as one line, hence tail -1 will grab the first occurrence which would be the nameserver rather than the response.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment