Best way to extract MAC address from ifconfig's output?

前端 未结 19 1653
面向向阳花
面向向阳花 2020-12-12 15:31

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

Sample output:

bash-3.00# ifconfig eth0        
eth0      Link          


        
相关标签:
19条回答
  • 2020-12-12 16:22

    this worked for me

    ifconfig eth0 | grep -o -E ..:..:..:..:..:..
    

    instead of eth0 you can write the interface you need it's mac address

    0 讨论(0)
  • 2020-12-12 16:24

    On Ubuntu 14.04 in terminal

    ifconfig | grep HW
    
    0 讨论(0)
  • 2020-12-12 16:26

    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
    
    0 讨论(0)
  • 2020-12-12 16:26

    Note: on OS X eth0 may not work. Use p2p0:

    ifconfig p2p0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'
    
    0 讨论(0)
  • 2020-12-12 16:27

    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.

    0 讨论(0)
  • 2020-12-12 16:28

    For Ubuntu/Debian

    ifconfig | grep HW | awk '{print $5}'
    

    For Rhat or CentOs try

    ip add | grep link/ether | awk '{print $2}'
    
    0 讨论(0)
提交回复
热议问题