背景:
需要通过shell脚本解析host。不想额外的下载工具,所以选择了ping命令。但是ping命令返回的不仅包含IP信息,所以需要截取字符串。网上的解决方案普遍存在遗留括号的问题,IPV4和IPV6两种情况兼容较差。
解决方案:
ipv4: ping $host -c1 | grep from | cut -d '(' -f2 | cut -d ')' -f1
ipv6: ping6 $host -c1 | grep from | cut -d '(' -f2 | cut -d ')' -f1
解释:
1、系统为centos6.7,PING结果返回如下。可以看到首行结果IPV4与IPV6格式有差异。因此初步过滤采用"grep from"过滤出包含from的行,而不是采用"grep PING"过滤。
# ping www.google.com
PING www.google.com (172.217.11.68) 56(84) bytes of data.
64 bytes from lax17s34-in-f4.1e100.net (172.217.11.68): icmp_seq=1 ttl=49 time=18.3 ms
64 bytes from lax17s34-in-f4.1e100.net (172.217.11.68): icmp_seq=2 ttl=49 time=18.4 ms
64 bytes from lax17s34-in-f4.1e100.net (172.217.11.68): icmp_seq=3 ttl=49 time=18.3 ms
64 bytes from lax17s34-in-f4.1e100.net (172.217.11.68): icmp_seq=4 ttl=49 time=18.6 ms
# ping6 www.google.com
PING www.google.com(lax17s34-in-x04.1e100.net (2607:f8b0:4007:802::2004)) 56 data bytes
64 bytes from lax17s34-in-x04.1e100.net (2607:f8b0:4007:802::2004): icmp_seq=1 ttl=53 time=8.30 ms
64 bytes from lax17s34-in-x04.1e100.net (2607:f8b0:4007:802::2004): icmp_seq=2 ttl=53 time=8.24 ms
64 bytes from lax17s34-in-x04.1e100.net (2607:f8b0:4007:802::2004): icmp_seq=3 ttl=53 time=8.27 ms
64 bytes from lax17s34-in-x04.1e100.net (2607:f8b0:4007:802::2004): icmp_seq=4 ttl=53 time=10.8 ms
1
2
3
4
5
6
7
8
9
10
11
12
13
# ping www.google.com
PING www.google.com (172.217.11.68) 56(84) bytes of data.
64 bytes from lax17s34-in-f4.1e100.net (172.217.11.68): icmp_seq=1 ttl=49 time=18.3 ms
64 bytes from lax17s34-in-f4.1e100.net (172.217.11.68): icmp_seq=2 ttl=49 time=18.4 ms
64 bytes from lax17s34-in-f4.1e100.net (172.217.11.68): icmp_seq=3 ttl=49 time=18.3 ms
64 bytes from lax17s34-in-f4.1e100.net (172.217.11.68): icmp_seq=4 ttl=49 time=18.6 ms
# ping6 www.google.com
PING www.google.com(lax17s34-in-x04.1e100.net (2607:f8b0:4007:802::2004)) 56 data bytes
64 bytes from lax17s34-in-x04.1e100.net (2607:f8b0:4007:802::2004): icmp_seq=1 ttl=53 time=8.30 ms
64 bytes from lax17s34-in-x04.1e100.net (2607:f8b0:4007:802::2004): icmp_seq=2 ttl=53 time=8.24 ms
64 bytes from lax17s34-in-x04.1e100.net (2607:f8b0:4007:802::2004): icmp_seq=3 ttl=53 time=8.27 ms
64 bytes from lax17s34-in-x04.1e100.net (2607:f8b0:4007:802::2004): icmp_seq=4 ttl=53 time=10.8 ms
2、然后只需要截取括号中的内容就可以了。这里使用cut命令截取。参数介绍。这里需要使用三个参数
1) "-d": 指定分割符。
2) "-f1": 截取匹配结果左侧内容。
3) "-f2": 截取匹配结果右侧内容。
3、"cut -d '(' -f2"命令截取"("右侧内容。
4、"cut -d ')' -f1"命令截取")"左侧内容。
5、最终获取的结果即是IP