Sorting Through Results of Revolving IPs from nslookup Results

If you are using something like imap.mail.yahoo.com or outlook.office365.com and would like to add a firewall rule to open the appropriate IPs to access could be quite a challenge. These IPs seem to change often. Here are a couple of command lines that may help sort through this mess.

Typically, a simple command would be executed with results.

nslookup outlook.office365.com

Since there are so many IPs that are cycled, and the desire is not to miss too many. Here is a loop performing 250 nslookups and outputting the IPs to a file. In this case, a new file will be created “>”. Optionally, the file could be appended with “>>”.

for i in {1..250}; do nslookup outlook.office365.com | grep "Address" | grep -v "#" | awk '{print $2}'; done > outlook.office365.com.ips

The results could be sorted with this.

cat outlook.office365.com.ips | sort -nr | uniq -c | sort -nr

To get a cleaner output, remove local IPs from the equation and group the IPs by the first two octaves of their IP range.

cat outlook.office365.com.ips | sort -nr | rev | cut -d"." -f3- | rev | uniq -c | sort -nr

These results may produce something like this, where the first column is the number of occurrences for that string followed by the first two octaves of the IP.

2153 132.245
58 157.56
15 40.96

Now, you could write something for 132.245.0.0/16 … etc.

An even cleaner method.

for i in {1..250}; do nslookup outlook.office365.com | grep "Address" | grep -v "#" | awk '{print $2}'; done | sort -nr | rev | cut -d"." -f3- | rev | uniq -c | sort -nr

The result:

2250 40.97
250 40.96