Wednesday, January 12, 2011

Find Active Hostnames Per Network

Here's a quick trick I use to find the hostnames of all active IPv4 devices in a subnet:

$ ssh routerIP.test.local 'sh arp | i Vlan70' | awk '{print $2}' | xargs -i dig -x {} +short
Password:
foo-tstsrv-01.test.local.
foo-gissrv-01.test.local.
foo-appsrv-01.test.local.
foo-filsrv-03.test.local.
foo-filsrv-02.test.local.

Translated into English:
  1. ssh routerIP.test.local 'sh arp | i Vlan70' displays the ARP table for Vlan 70 on the router acting as the default gateway for that VLAN.
  2. awk '{print $2}' extracts the second field from the output, which is the IPv4 address for the ARP entry.
  3. xargs -i dig -x {} +short takes each one of those IPv4 addresses and queries DNS for the hostname associated with the IP address (that is, the PTR record), using the "dig -x" command, with the +short parameter to display only the hostname. The {} syntax is a part of the xargs command which causes the output from the previous command (that is, the awk command output which produces just an IPv4 address) to be inserted in the place of the {} characters.
To run this on Windows, you need to have both Cygwin and the dig command installed.

No comments: