我有任务从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($2,var,"/*"); print $1,":",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.]+).*/\1/p'
当前我只能提取IP地址。
任何帮助都受到赞赏。
答案 0 :(得分:1)
也许不是最聪明的解决方案,但是您可以尝试一下:
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)
答案 1 :(得分:1)
如果只有csh
(默认为FreeBSD shell)并且需要获取-l
上的接口-u
的IP,则可以尝试以下操作:>
$ foreach i (`ifconfig -lu`)
ifconfig $i | awk -v i=$i '/inet6?/{print i ": " $2}'
end
这将以以下格式返回IPv4和IPv6地址:
<interface>: IP
-l
标志可用于列出系统上所有可用的接口,选项
-u
将此限制为已启动的接口。
如果您只需要IPv4(inet
),则可以使用类似的内容:
$ foreach i (`ifconfig -lu`)
ifconfig $i inet | awk -v i=$i '/inet6?/{print i ": " $2}'
end
答案 2 :(得分:1)
尝试
for ifcfg in $(ifconfig -lu)
do
ifconfig $ifcfg | grep -v inet6 | awk -v ifcfg=$ifcfg '/inet6?/{print ifcfg " : " $2}'
done
希望有帮助。
答案 3 :(得分:0)
您还可以通过以下脚本提取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 "," $2}' | 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