I almost always need to get the remote mac address of a machine on my network. When I do I use a simple bash script that I wrote.
mac.sh:
#!/bin/sh
ping -oc2 $1 > NULL
arp -n $1 | awk '{print $4}' | sed 'y/abcedf/ABCEDF/' | sed 's/^\([0-9A-F]:\)/0\1/' | sed 's/:\([0-9A-F]\):/:0\1:/g' | sed 's/:\([0-9A-F]\):/:0\1:/g' | sed 's/:\([0-9A-F]\)$/:0\1/'
exit 0
Usage:
./mac.sh [hostname or IP address]
Examples:
./mac.sh hematite
./mac.sh 10.0.1.2
Output (if your computer can successfully get an arp address):
08:00:07:1A:46:09
Output (if your computer can not ping):
[delay....]
no
Output (if you are trying to get your computers mac address):
no
Output (if you are trying to get a computer outside of your lan):
no
Output (for a machine on the same LAN but you have no route):
(inComplEtE)
Script dissected:
ping -oc2 $1 > NULL
Will try to ping whatever computer (10.0.1.2 in the example above) two times, and it will quit after receiving one ping echo response. It will not display anything to the terminal because the output is redirected to NULL.
arp -n $1
Will retrieve the layer-2 mac address from your computer's arp database, if it exists.
Output from example above:
? (10.0.1.2) at 8:0:7:1a:46:9 on en1 [ethernet]
| awk '{print $4}'
Will grab just the mac address.
Output from example above:
8:0:7:1a:46:9
| sed 'y/abcedf/ABCEDF/'
Will convert lower-case to upper-case for the letters A-F.
Output from example above:
8:0:7:1
A:46:9
| sed 's/^\([0-9A-F]:\)/0\1/'
Will add a '0' in front of the first HEX value if it needs one.
Output from example above:
08:0:7:1A:46:9
| sed 's/:\([0-9A-F]\):/:0\1:/g' | sed 's/:\([0-9A-F]\):/:0\1:/g'
Will add a '0' in all other areas as needed in the mac address, except for the last HEX value. You will notice that this line is essentially one search & replace repeated two times, this is because the search finds :#:, but would skip the second HEX value ie: :#:#:.
Output from example above:
08:
00:
07:1A:46:9
| sed 's/:\([0-9A-F]\)$/:0\1/'
This last line will add a '0' in the final HEX value if needed.
Output from example above:
08:00:07:1A:46:
09
-Brian
Further reading on sed, grep, & awk:
http://tweaksandpics.com/advanced-shell-scripting-awk-sed-and-grep/
http://www.toannguyen.com/moresed.html
More info on backreferences:
http://www.regular-expressions.info/brackets.html