将mac地址打印到文件

mic*_*con 8 linux shell ethernet mac-address

使用 bash 脚本,我可以读取 eth0 的 mac 地址并将其打印到文件中吗?

Mic*_*zek 15

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 
Run Code Online (Sandbox Code Playgroud)

HWaddr就是你想要的,所以你可以awk用来过滤它:

$ ifconfig eth0 | awk '/HWaddr/ {print $NF}'
00:11:22:33:44:55
Run Code Online (Sandbox Code Playgroud)

将其重定向到一个文件中:

$ ifconfig eth0 | awk '/HWaddr/ {print $NF}' > filename
Run Code Online (Sandbox Code Playgroud)

  • 国际上的做法是`LC_ALL=C ifconfig eth0 | awk '/HWaddr/ {print $NF}'`,因为输出可能是本地化的,与 'HWaddr' 不匹配。LC_ALL=C 使用国际标准。 (3认同)
  • 你也可以使用 `ip` 命令:`/sbin/ip link show eth0`。 (2认同)
  • @Michael 在 Linux 上,它是 [首选工具](http://lartc.org/lartc.html#LARTC.IPROUTE2.WHY)。实际上你必须使用来配置一些高级功能。但是 ifconfig 存在于...... (2认同)
  • @user 啊,很酷。据我所知,它永远是第一行,所以你可以使用 `awk'{print $NF; 也退出}'` (2认同)

cam*_*amh 10

这是一个现代的 Linux 方法:

ip -o link show dev eth0 | grep -Po 'ether \K[^ ]*'
Run Code Online (Sandbox Code Playgroud)

这是现代在ifconfig已经长期被否决有利于ipiproute2包装,并grep具有-P针对Perl的正则表达式选项零宽度正向后看断言

grep -o非常适合文本提取。sed传统上用于此,但我发现 perl 样式的零宽度断言比 sed 替换命令更清晰。

你实际上并不需要-o(oneline) 选项ip,但我更喜欢在提取网络信息时使用它,因为我发现每行一条记录更干净。如果您要进行更复杂的匹配或提取(通常使用awk),-o对于干净的脚本来说是必不可少的,因此为了一致性和通用模式,我总是使用它。

编辑:10 年后更新:ip现在有-jJSON 输出的标志,当与 结合时jq,它提供了一个更健壮和可读的命令管道:

ip -j link show dev eth0 | jq -r '.[0].address'
Run Code Online (Sandbox Code Playgroud)

使其输出原始字符串而不是带引号的 (JSON) 字符串的-r标志jq


cjm*_*cjm 5

#! /bin/sh

/sbin/ifconfig eth0 | perl -ne 'print "$1\n" if /HWaddr\s+(\S+)/' >file
Run Code Online (Sandbox Code Playgroud)

当然,还有其他工具可以从ifconfig的输出中删除 MAC 地址。我只是喜欢 Perl。