以下是我的 ifconfig 输出
eth0 Link encap:Ethernet
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
Interrupt:28 Base address:0x2000
eth1 Link encap:Ethernet
inet addr:192.168.1.2 Bcast:192.168.1.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:36497 errors:0 dropped:0 overruns:0 frame:14515
TX packets:44884 errors:1352 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:20781745 (20.7 MB) TX bytes:17776225 (17.7 MB)
Interrupt:17 Base address:0xc000
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:12 errors:0 dropped:0 overruns:0 frame:0
TX packets:12 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:720 (720.0 B) TX bytes:720 (720.0 B)
virbr0 Link encap:Ethernet
inet addr:192.168.122.1 Bcast:192.168.122.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:24 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:4416 (4.4 KB)
vmnet1 Link encap:Ethernet
inet addr:192.168.185.1 Bcast:192.168.185.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:24 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
vmnet8 Link encap:Ethernet
inet addr:192.168.207.1 Bcast:192.168.207.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:25 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
如何使用grep提取每个LAN卡对应的IP地址?
这可能吗?如何实现?
答案1
$ ip -o addr show | awk '/inet/ {print $2, $3, $4}'
lo inet 127.0.0.1/8
lo inet6 ::1/128
eth0 inet 192.168.0.1/24
eth0 inet6 fe80::2a0:feed:dead:beef/64
答案2
哦天哪,我忍不住想尝试一下提高我的 perl oneliner 脚本能力当我看到这样的帖子时。这是第一次黑客尝试:
$ /sbin/ifconfig | \
perl -ane "(\$n)=(/^(\S+)/) and print \"\$n: \"; print (/addr:(\S+)/) and print \"\n\" if /inet/"
eth0: 192.168.0.11
lo: 127.0.0.1
这可能需要进一步严格,而且它还存在很多问题,例如它不能处理 IPv6 地址等等。
答案3
我是这样做的:
ETHERADD=$(/sbin/ifconfig |grep -e ^[a-z] |grep -v lo | awk '{ printf $1 FS}')
for i in $ETHERADD
do
IP=$(/sbin/ifconfig $i | grep -o '[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*' | head -1)
printf "%-16s%-42s*\n" "IP $i:" "$IP"
done
答案4
这是我使用的
#!/bin/bash
interfaces=$(/sbin/ifconfig |grep -e ^[a-z] | awk '{ printf $1 " "}')
for i in $interfaces
do
addr=$(/sbin/ifconfig $i | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}')
addr6=$(/sbin/ifconfig $i | grep 'inet6 addr:' |sed 's/ *//g'| cut -d' ' -f3 | cut -d'/' -f1)
echo "$i inet4 $addr inet6 $addr6"
done