使用Shell脚本获取MAC地址 [英] Get MAC address using shell script

查看:1622
本文介绍了使用Shell脚本获取MAC地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,提到的用于获取MAC地址的所有解决方案始终使用eth0. 但是,如果接口不是以eth0开头,该怎么办呢?同样在OS X上,接口名称也不同.
接口eth0可能也存在但未被使用.即未激活,它没有IP.

Currently all the solution mentioned for getting the MAC address always use eth0. But what if instead of eth0 my interfaces start with eth1. Also on OS X the interface names are different.
Also the interface eth0 may be present but is unused. i.e. not active, it doesn't have an IP.

那么有什么办法可以获取第一个可用接口Active的MAC地址(即,它有一个inet地址,我什至不希望有人拥有inet6).

So is there a way I could get the MAC address for the first available interface that is Active.(i.e. it has an inet address, I even don't want one having inet6).

例如

eth0      Link encap:Ethernet  HWaddr <some addr>
          inet6 addr: <some addr> Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:123
          RX packets:123 errors:123 dropped:123 overruns:123 frame:123
          TX packets:123 errors:123 dropped:123 overruns:123 carrier:123
          collisions:123 txqueuelen:123 
          RX bytes:123 (123 MB)  TX bytes:123 (123 KB)
          Interrupt:123 Memory:00000000-00000000

eth1      Link encap:Ethernet  HWaddr <some addr>
          inet addr:<some addr>  Bcast:<some addr>  Mask:<some addr>
          inet6 addr: <some addr> Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:123 Metric:123
          RX packets:123 errors:123 dropped:123 overruns:123 frame:123
          TX packets:123 errors:123 dropped:123 overruns:123 carrier:123
          collisions:123 txqueuelen:123 
          RX bytes:123 (123 MB)  TX bytes:123 (123 KB)
          Interrupt:123 Memory:00000000-00000000

注意:我已经更改了输出值.

NOTE : I have changed the values of the output.

因此,在这种情况下,我想要的是eth1而不是eth0的HWaddr. 我如何找到它?此外,它还应适用于所有Linux版本.

So in this case I want the HWaddr for eth1 and not eth0. How do I find it ? Also it should work on all the Linux flavours.

推荐答案

观察到接口名称和MAC地址是一行中的开头和结尾字段,没有前导空格.

Observe that the interface name and the MAC address are the first and last fields on a line with no leading whitespace.

如果缩进的一行之一包含inet addr:,则应打印最新的接口名称和MAC地址.

If one of the indented lines contains inet addr: the latest interface name and MAC address should be printed.

ifconfig -a |
awk '/^[a-z]/ { iface=$1; mac=$NF; next }
    /inet addr:/ { print iface, mac }'

请注意,多个接口可以满足您的条件.然后,脚本将打印多行. (如果您始终只想打印第一个匹配项,则可以在最后一个大括号之前添加; exit.)

Note that multiple interfaces could meet your criteria. Then, the script will print multiple lines. (You can add ; exit just before the final closing brace if you always only want to print the first match.)

这篇关于使用Shell脚本获取MAC地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆