从 ifconfig 中提取 IP 地址和接口名称

Extracting ip address and interface name from ifconfig

我有任务从 ifconfig 中提取 IP 地址和接口列表。

OS FreeBSD

ifconfig 输出:

em0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
        options=9b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM>
        ether 00:50:56:a5:42:13
        inet 192.168.1.5 netmask 0xfffffff0 broadcast 192.168.1.255
        inet6 fe80::250:56ff:fea1:4213%em0 prefixlen 64 scopeid 0x1
        nd6 options=29<PERFORMNUD,IFDISABLED,AUTO_LINKLOCAL>
        media: Ethernet autoselect (1000baseT <full-duplex>)
        status: active
em1: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
        options=9b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM>
        ether 00:50:56:a1:62:19
        inet 172.16.16.16 netmask 0xfffffffc broadcast 172.16.16.255
        inet6 fe80::250:56ff:fea1:6229%em1 prefixlen 64 scopeid 0x2
        nd6 options=29<PERFORMNUD,IFDISABLED,AUTO_LINKLOCAL>
        media: Ethernet autoselect (1000baseT <full-duplex>)
        status: active
br0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
        options=9b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM>
        ether 00:50:56:a1:55:27
        inet 10.10.10.11 netmask 0xffffff00 broadcast 10.10.10.255
        inet6 fe80::250:56ff:fea1:5507%em2 prefixlen 64 scopeid 0x3
        nd6 options=29<PERFORMNUD,IFDISABLED,AUTO_LINKLOCAL>
        media: Ethernet autoselect (1000baseT <full-duplex>)
        status: active

我想要这样的输出:

em0 : 192.168.1.5
em1 : 172.16.16.16
br0: 10.10.10.11

ifconfig | awk '/inet / {split(,var,"/*"); print ,":",var[1]}'

ifconfig | grep -o "inet [0-9]*\.[0-9]*\.[0-9]*\.[0-9]*" | grep -o "[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*"

ifconfig | sed -En -e 's/.*inet ([0-9.]+).*//p'

目前只能提取ip地址

非常感谢任何帮助。

也许不是最明智的解决方案,但您可以尝试一下:

while read line
do
  [[ "$line" =~ ^[a-z]+[0-9]: ]] && {
     var=$(echo "$line" | cut -d' ' -f1)
     ip=$(grep -A3 "$var" <(ifconfig)  | grep -oP 'inet.{0,15}' | cut -d' ' -f2)
     echo "$var" "$ip"
  }
done < <(ifconfig)

如果你只有 csh (default FreeBSD shell) 并且需要获取接口 -l 的 IP 地址 -u,你可以试试这个:

$ foreach i (`ifconfig -lu`)
ifconfig $i | awk -v i=$i '/inet6?/{print i ": " }'
end

这将 return 格式的 IPv4 和 IPv6 地址:

<interface>: IP

来自ifconfig man

The -l flag may be used to list all available interfaces on the system,

Option -u limits this to interfaces that are up.

如果您只需要 IPv4 (inet),您可以使用类似的东西:

$ foreach i (`ifconfig -lu`)
ifconfig $i inet | awk -v i=$i '/inet6?/{print i ": " }'
end

尝试

for ifcfg in $(ifconfig -lu)
do
   ifconfig $ifcfg | grep -v inet6 | awk -v ifcfg=$ifcfg '/inet6?/{print ifcfg " : " }'
done

希望对您有所帮助。

您也可以通过以下脚本提取 MAC:

for ifcfg in $(ifconfig -lu)
do
    mac=$(ifconfig $ifcfg | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}')
    ifconfig $ifcfg | grep -v inet6 | awk -v ifcfg=$ifcfg,$mac '/inet6?/{print ifcfg mac "," }' | grep -v lo
done

输出:

em0,00:50:56:a5:42:13,192.168.1.5
em1,00:50:56:a1:62:19,172.16.16.16