Best way to extract MAC address from ifconfig'

2019-01-21 04:28发布

What is the best way to extract the MAC address from ifconfig's output?

Sample output:

bash-3.00# ifconfig eth0        
eth0      Link encap:Ethernet  HWaddr 1F:2E:19:10:3B:52    
          inet addr:127.0.0.66  Bcast:127.255.255.255  Mask:255.0.0.0    
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          ....
          ....

Should I use cut, AWK or anything else, and what are the merits and demerits of one method over the other.

17条回答
Explosion°爆炸
2楼-- · 2019-01-21 04:57

Not sure whether there really are any advantages, but you can simply use awk:

ifconfig eth0 | awk '/HWaddr/ {print $5}'
查看更多
SAY GOODBYE
3楼-- · 2019-01-21 04:59
ifconfig | grep HW | awk '{print $5}'

For Rhat or CentOs try ip add | grep link/ether | awk '{print $2}'

查看更多
我命由我不由天
4楼-- · 2019-01-21 05:07

How about this one:

ifconfig eth0 | grep -Eo ..\(\:..\){5}

or more specifically

ifconfig eth0 | grep -Eo [:0-9A-F:]{2}\(\:[:0-9A-F:]{2}\){5}

and also a simple one

ifconfig eth0 | head -n1 | tr -s ' ' | cut -d' ' -f5`
查看更多
冷血范
5楼-- · 2019-01-21 05:08

I needed to get MAC address of the active adapter, so ended up using this command.

ifconfig -a | awk '/^[a-z]/ { iface=$1; mac=$NF; next } /inet addr:/ { print mac }' | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'

Hope it helps.

查看更多
狗以群分
6楼-- · 2019-01-21 05:10

I like using /sbin/ip for these kind of tasks, because it is far easier to parse:

$ ip link show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast qlen 1000
    link/ether 00:0c:29:30:21:48 brd ff:ff:ff:ff:ff:ff

You can trivially get the mac address from this output with awk:

$ ip link show eth0 | awk '/ether/ {print $2}'
00:0c:29:30:21:48

If you want to put a little more effort in, and parse more data out, I recommend using the -online argument to the ip command, which will let you treat every line as a new device:

$ ip -o link 
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue \    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast qlen 1000\    link/ether 00:0c:29:30:21:48 brd ff:ff:ff:ff:ff:ff
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast qlen 1000\    link/ether 00:0c:29:30:21:52 brd ff:ff:ff:ff:ff:ff
4: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast qlen 100\    link/[65534] 
5: sit0: <NOARP> mtu 1480 qdisc noop \    link/sit 0.0.0.0 brd 0.0.0.0
查看更多
SAY GOODBYE
7楼-- · 2019-01-21 05:10

This works for me on Mac OS X:

ifconfig en0 | grep -Eo ..\(\:..\){5}

So does:

ifconfig en0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'

Both are variations of examples above.

查看更多
登录 后发表回答