Return MAC address of active interfaces in local network with a Bash script
I have an Ubuntu server in a local network that has a number of other devices on the network, both LAN and wireless. I would like to run a Bash script to find out the MAC address (only one per machine) of the interface that开发者_运维技巧 is in use on all the machines in the local network. This means depending on what someone's laptop was using (LAN or wireless or other) that it would return only address of the active interface.
I'm not sure which command to use (maybe arp?). ifconfig
works only for my local machine, but I would like to do something like this regular expression from Stack Overflow question Best way to extract MAC address from ifconfig's output?.
How can I do this?
Most unixes provide an "UP" flag on the flags line of the ifconfig(8) output for interfaces that are enabled, you could match on that.
eth0 Link encap:Ethernet HWaddr 00:01:29:a3:f6:1d
inet addr:192.168.0.254 Bcast:192.168.0.255 Mask:255.255.255.0
inet6 addr: fe80::201:29ff:fea3:f61d/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:35163720 errors:0 dropped:0 overruns:0 frame:0
TX packets:36652372 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:32425323589 (32.4 GB) TX bytes:4255769808 (4.2 GB)
Interrupt:17
(note the UP
on the 4th line)
However you can have more than one interface enabled, in which case you might have to look at routing to work out which interface would be used for the path to the default route (ifconfig -rn will help in this)
$ netstat -rn
Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
.
.
.
0.0.0.0 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
here the 0.0.0.0
entry is the default route, 192.168.0.1 will be the host that will be used as the default route and and eth0 is the interface the traffic will be passed over.
This is easily doable with the UNIX arp command, but you'll only see MAC addresses for hosts that are in your ARP table. The best way to populate the table with every host on your subnet is to use nmap with the -sP arg.
In short:
netstat -rn (local subnet/mask)
then
/sbin/arp -n
精彩评论