Answers:
ifconfig 将输出有关您的接口的信息,包括MAC地址:
$ ifconfig eth0
eth0 Link encap:Ethernet HWaddr 00:11:22:33:44:55
inet addr:10.0.0.1 Bcast:10.0.0.255 Mask:255.0.0.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:289748093 errors:0 dropped:0 overruns:0 frame:0
TX packets:232688719 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:3264330708 (3.0 GiB) TX bytes:4137701627 (3.8 GiB)
Interrupt:17
该HWaddr是你想要的,所以你可以使用awk过滤它:
$ ifconfig eth0 | awk '/HWaddr/ {print $NF}'
00:11:22:33:44:55
将其重定向到文件中:
$ ifconfig eth0 | awk '/HWaddr/ {print $NF}' > filename
LC_ALL=C ifconfig eth0 | awk '/HWaddr/ {print $NF}',因为输出可能是本地化的,不匹配“ HWaddr”。LC_ALL = C使用国际标准。
awk '{print $NF; exit}'太多
| head -n 1then。
这是现代的Linux方法:
ip -o link show dev eth0 | grep -Po 'ether \K[^ ]*'
这是现代在ifconfig已经长期被否决有利于ip从iproute2包装,并grep具有-P针对Perl的正则表达式选项零宽度正向后看断言。
grep -o非常适合文本提取。sed通常用于此目的,但我发现perl样式的零宽度断言比sed替换命令更清晰。
实际上,您实际上不需要-o(oneline)选项ip,但是我更喜欢在提取网络信息时使用它,因为我发现它更干净,每行只有一条记录。如果您要进行更复杂的匹配或提取(通常使用awk),-o这对于干净的脚本是必不可少的,因此,为了保持一致性和通用模式,我总是使用它。
#! /bin/sh
/sbin/ifconfig eth0 | perl -ne 'print "$1\n" if /HWaddr\s+(\S+)/' >file
当然,还有其他工具可以将MAC地址从ifconfig输出中切出。我只是喜欢Perl。
ip命令:/sbin/ip link show eth0。