shell 截取ip地址最后一位_shell脚本:截取ping命令中的IP

背景:

需要通过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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值