4

I am trying to make a script to run constantly that produces a log showing ping stats. I want the log to contain and ping fails, times over 500ms and the traceroute of any timeouts. Here my script:

#!/bin/bash
ip=www.google.com
while [ 1 ]; do
ping -c 1 $ip 1> /dev/null
result=$?
if [ $result == "1" ]; then
echo FAIL on `date` >> ~/ping.log
echo FAIL on `date`.  Doing tracert!
traceroute $ip >> ~/ping.log
fi
if [ $result == "0" ]; then
echo SUCCEED on `date` >> ~/ping.log
echo SUCCEED on `date`
fi
sleep .4
done

I copied this script from another site.

Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227

2 Answers2

3

You might want to take a look at fping and it's -t option:

-t n

Initial target timeout in milliseconds (default 500). In the default mode, this is the amount of time that fping waits for a response to its first request. Successive timeouts are multiplied by the backoff factor.

By using fping you can just check the exit status without the need of parsing the output:

IP=121.78.67.31; fping -c1 -t200 $IP || traceroute $IP
FloHimself
  • 11,272
  • 3
  • 22
  • 24
1

line

ping -c 1 $ip 1> /dev/null

discard result, so you can't know if you pings are over 500 ms.

use

ping -c 1 $ip 1> /tmp/ping.txt

to keep ping's response, then

in the part where ping is sucessfull

awk -F/ 'NF>5 { if ( $5 > 500 ) exit 1 ; else exit 0 }'  /tmp/ping.txt

will give 0 under 500 ms and 1 if average ping is over 500 ms.


ping result looks like

PING 172.18.15.22 (172.18.15.22) 56(84) bytes of data.
64 bytes from 172.18.15.22: icmp_seq=1 ttl=64 time=0.237 ms

--- 172.18.15.22 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.237/0.237/0.237/0.000 ms

awk will

  • -F/ use / as separator
  • NF>5 pick line with at least /
  • if ( $5 > 500 ) test average value
  • exit 1 / exit 0 givre proper return code
Archemar
  • 31,183
  • 18
  • 69
  • 104
  • I am wanting to put in a log file when and individual ping is over a certain time not the average. Thanks for the help though. – Eric Pevehouse May 28 '15 at 13:31
  • ?? You say "I want the log to contain and ping fails, times over 500ms " So, I use 500 as an example, the comment issue only one ping at a time, my awk solution give you a way to test if an individual ping is over 500ms. Please do accept my apologies for not understanding your question. – Archemar May 28 '15 at 13:41