使用cut过滤ping的输出

时间:2018-05-30 01:03:28

标签: bash filter cut traceroute

我的互联网服务提供商遇到了问题。

尽管已经设置了一个烟雾ping服务器,该服务器清楚地显示了数据包丢失导致间歇性的延迟峰值,但他们已经要求为每个冒烟服务器目标提供跟踪路由;没有延迟/丢失时设置一个,有时设置另一个设置。

我理解他们为什么要问,他们想知道是否存在某种路由问题。

我创建了一个脚本,可以立即跟踪所有目标并输出到文件,但我需要开发一个脚本,当延迟超过某个值时调用traceroute脚本。

为此,我制作了以下脚本,但它失败了,因为剪切不仅包括数字而且包括“ms”。如何进一步过滤其输出以包含数字?

#/bin/bash

while :
    if [ ping | cut -f5 d" " -gl 400 ]
    then
        wait 15
  else
    ./path/script
    fi
done

2 个答案:

答案 0 :(得分:0)

使用sed获取整数部分并将ping计数限制为1

#/bin/bash

while :
    ttl=$(ping -n -c1 www.google.com | sed -nre 's/^.* time=([0-9]+)\.[0-9]+ ms$/\1/p')
    if [ "$ttl" -gl 400 ]
    then
        wait 15
else
    ./path/script
    fi
done

答案 1 :(得分:0)

你真的只需要这样的东西:

android:minLines="3"

但是我会使用CURL而不是ping和traceroute,这可以被阻止等等。(我有一个如何获得下面的ms的例子)

ping_res="64 bytes from ya-in-f104.1e100.net (173.194.219.104): icmp_seq=7 ttl=36 time=14.5 ms"
echo $ping_res | awk '{print $7}' | cut -d'=' -f2
36

更多awk / cut示例:

#!/usr/bin/env bash

    # -- BASH4+ example
    # -- if latency is exceeds max_lat, do something . 

    readonly max_lat="3.1415" # made up number
    readonly url="http://www.google.com/"
    readonly curl_timeout="60"
    readonly delay=120 # seconds

    while [ 1 ] ; do

        val=$(curl -o /dev/null -L -s -w "%{time_total}\n" --max-time ${curl_timeout} "${url}" )

        if [ 1 -eq "$(echo "${val} <= ${max_lat}" | bc)" ] ; then
            echo "${val} <= ${max_lat}, doing something ... "
            ./path/script
        else
            echo "just going to wait $delay seconds and test again .."
            sleep $delay
        fi

    done

OR

echo $ping_res
64 bytes from ya-in-f104.1e100.net (173.194.219.104): icmp_seq=7 ttl=36 time=14.5 ms
$ echo $ping_res | awk '{print $5}'
(173.194.219.104):
$ echo $ping_res | awk '{print $5}' | cut -d'(' -f2
173.194.219.104):
$ echo $ping_res | awk '{print $5}' | cut -d'(' -f2 | cut -d')' -f1
173.194.219.104

请参阅:

How do I measure request and response times at once using cURL?

PS&GT;我可能会从你的例子中反转它(-gl不存在),但你明白了。

相关问题