Monday, October 29, 2007

Sorting IP Addresses with Linux/Unix "sort"

Recently I was doing a site survey of all active IPs on our network. I used nmap for this function and dumped all responding IP addresses to a text file. I don't have to worry about PC's not responding to the ping due to a personal firewall since our PC's here do not have one turned on; they are all protected by our corporate firewall. To find all responding IP's I ran the following command line for nmap:
/usr/bin/nmap -n -sP xxx.xxx.xxx.xxx-xxx xxx.xxx.xxx.xxx-xxx >> /home/myUserName/IPdb/site1IPsUp.txt
I did this for several times a day, several days a week for a couple weeks to make sure I had gotten the most complete picture possible, then I tried to sort them...

IP addresses are a strange animal, they aren't really "numbers" per se due to multiple decimal points and they aren't really words, they are a sort of hybrid. Because of this using sort without so pretty specific command line arguments won't give you what you want, which is numerically proper sorting.

Also, nmap outputs a bunch of junk text which I'm not interested in at all, I want this removed and just want the IP addresses themselves. Since I've done this survey over and over again I'm going to have dozens of the same IP address show up in the file, I only want to see it listed once. After all is said and done this is the command line I finished with to give me the output I was looking for:
cat site1IPsUp.txt | grep -v Nmap | grep -v Starting | awk '{ print $2 }' | sort -u -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4

From there I can do with it what I like. ;)

No comments: