Articles

Wednesday, December 14, 2011

Get the MAC Address of All Systems on Your Subnet Remotely

Several years ago I interning and was tasked with updating the DHCP reservations on a FreeBSD DHCP server. The Network Administrator told me to go around to each machine and write down the IP Address and it's MAC Address. I thought to myself, there's no way in hell I'm walking around to every system in the building and doing that. How did I do it? I wrote a handy script called getMAC.bat:


@echo off
setlocal enabledelayedexpansion
if [%1] == [] (
  echo.
  echo Please specify a Subnet or IP address.
  echo Example: 192.168.1.0 or 192.168.1.10
  goto :eof
)
arp -d > nul
for /f "tokens=1-4 delims=." %%a in ('echo %1') do (
if not "%%d"==0 (
ping -n 1 -w 5 %1 > nul
for /f "tokens=1,2 delims= " %%x in ('arp -a ^| findstr "%1"') do (
echo.&&echo %%x %%y
goto :eof
)
)
for /l %%i in (1 1 254) do (
set ip=%%a.%%b.%%c.%%i
ping -n 1 -w 5 !ip! > nul
if [!errorlevel!]==[0] (
call :_print !ip!
)
)
)
:_print
for /f "tokens=1,2 delims= " %%x in ('arp -a ^| findstr "%1"') do (
echo %%x %%y
)

Sample run:

getMAC 192.168.1.0
192.168.1.1     00-21-29-b9-22-9d
192.168.1.3     00-26-4a-ee-84-c4
192.168.1.5     00-23-a5-00-06-a2
192.168.1.7     e0-cb-4e-39-b6-40
192.168.1.10    00-0c-29-53-3f-6f
192.168.1.11    00-0c-29-2e-c2-ab

You could also redirect the output to a file for later parsing:
getMAC 192.168.1.0 > outfile.txt

You can also specify just a single IP address to retrieve the MAC Address for:
getMAC 192.168.1.7
e0-cb-4e-39-b6-40

And people say batch scripts aren't useful.

How does it work? It works by pinging each machine and then comparing that IP address against the local machines ARP table to see if it exists. If it does, it prints the IP address and its corresponding MAC address.

This turned manual task that would have taken a couple hours into just a couple minutes of waiting for the script to finish.
Keep in mind this was a fairly small network with roughly 100 nodes. It was a /24 (255.255.255.0) network on a 192.168.10.0 subnet. A couple more things to keep in mind is that I set the ICMP ECHO REPLY timeout to 5 milliseconds with the -w 5 switch to speed up the script. The caveat with this is that any node that takes longer than 5ms to reply will not be found. This can easily be adjusted if your network has higher latency.

Obviously this will only work on a /24. Perhaps if I get tasked with something similar I'll update the script to work on additional networks like 10.0.0.0/18, but at that point I'd be trying to write a subnet calculator in pure batch. : ) This was just an exercise in batch scripting to see what I could come up.

dcprom0



No comments:

Post a Comment