A couple posts down, I was parsing the nslookup command to get hostnames. Even easier, use the host command. The hostname seems to be the fifth string after spaces, so using cut, it might look something like:
host <ip> | cut -d " " -f5
But there will be a period at the end, so just clean that up. Next is to get the IP and the hostname in some easy format, like colon or pipe delimited.
860 total views, 1 views today
So today I had to convert IP addresses to hostnames. Seems easy enough, just use nslookup. But I had more than 400 IPs that needed to be converted. Ugh. So we need to do a little parsing.
First, take the IP addresses and get the host information. Let’s script this.
for ip in $(cat ips.txt); do
nslookup $ip >> nslookups.txt
This will do an nslookup for each of the IPs in the ips.txt file. Great! Now we need to parse it. This should be pretty easy to just look for “name=” except sometimes, there isn’t a hostname and then “name=” doesn’t appear. So instead we look for something else that is always in there, regardless of whether there is a hostname. It seems the string “arpa” matches this. So the next step is to find that and then cut the hostname, or something that doesn’t look like a hostname if there isn’t one.
grep arpa nslookups.txt | cut -d " " -f3 > hostnames.txt
When this finishes, the hostnames.txt file will have one string per line, either the hostname or the word “can’t”. At this point, do a find/replace for “can’t” and make it blank (since there isn’t a hostname for that IP).
Now you have two files, one with all the IPs and one with the hostnames. Put them in two Excel columns and match them up. There is one more problem here that I haven’t found a good solution for yet. Some of the IPs may have more than one hostname. So when you match up the columns in Excel, you’ll likely have more hostnames than IPs. Unfortunately the only solution I have so far is to read through the nslookups.txt file, find the entries with more than one hostname and then manually fix this in the Excel file. It takes a little bit of time, but definitely better than running nslookup manually hundreds of times.
1,216 total views