tnt5273
tnt5273

Reputation: 79

shell script to check ping packet loss & avg latency on AIX

I'm trying to create script which will ping to remote server and displays only 1) % packet loss 2) average round trip latency in ms

for packet loss i created line

`ping -c 3 -s 14 x.x.x.x|grep packet|awk '{print $7}'|cut -d'%' -f1`

which only gives packet loss,

my problem starts when ip is not reachable output of line changes and hence i'm not able to capture both

for reference i'm showing output of both scenarios

   `/pefmephbir >ping -c 3 -s 14 10.9.50.225`
  PING 10.9.50.225 (10.9.50.225): 14 data bytes

  --- 10.9.50.225 ping statistics ---
  **3 packets transmitted, 0 packets received, 100% packet loss**


  `/pefmephbir >ping -c 3 -s 14 10.9.50.220`
  PING 10.9.50.220 (10.9.50.220): 14 data bytes
  22 bytes from 10.9.50.220: icmp_seq=0 ttl=63 time=0 ms
  22 bytes from 10.9.50.220: icmp_seq=1 ttl=63 time=0 ms
  22 bytes from 10.9.50.220: icmp_seq=2 ttl=63 time=0 ms

  --- 10.9.50.220 ping statistics ---
  **3 packets transmitted, 3 packets received, 0% packet loss
  round-trip min/avg/max = 0/0/0 ms**

hope someone with expertise in scripting can help me out

TIA

Upvotes: 1

Views: 8091

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207455

Try this:

ping ... | awk '/packet loss/{x="Loss:" $7} /round-trip/{x="Trip:" $4} END{print x}'

If it sees a line with "packet loss" in it, it creates a string x with the packet loss percentage. If it sees a line with "round-trip" it overwrites the string x with the round trip time. At the end, it prints whatever the string x is set to.

In the light of your comments...

awk '/packet loss/ && /100/{x="Loss: " $7} /round-trip/{split($4,a,/\//);x="Ave: " a[2]} END{print x}'

So, now the "packet loss" line must also contain "100" before we pick it up. And the 4th field of the "round-trip" line is split into an array a[] using / as separator, then we take the second element of a[] as the average and store that in our output string x.

Upvotes: 2

perreal
perreal

Reputation: 97948

Using sed:

ping ... | sed -n -e 's/.*\(100% packet loss\).*/\1/p' \
                  -e 's_.*min/avg/max = [0-9]*/\([0-9]*\)/[0-9]*.*_\1_p'

Upvotes: 2

Related Questions