Attempting to write a script to eventually notify me via email for when there is packetloss across the backbone. I am looking for values greater than 0% in the mtr field.
#!/bin/sh
target=www.google.com
date +"%D"_"%T" >> /home/rich/mtr.log
echo "----------------------------------------" >> /home/rich/mtr.log
mtr -report -c 5 $target >> /home/rich/mtr.log
mtrlog=`cat /home/rich/mtr.log | awk '/%/ { print $2 }'`
zeroloss=0%
if [ "$mtrlog" = "$zeroloss" ] ; then
echo "No packetloss"
fi
With what I have above, it's echoing more than one 0% for the mtr field ( obiously) and comparing it to the zeroloss of 0% which results in it not echoing no packetloss. Do I need a for loop in there for each line?
Example when stripping script to just variables it comes up with:
I'm not familiar with the 'mtr' command, but I'll guess that its sending out pings and presenting a summary that includes packet loss. Your getting tripped up because you are parsing the whole log file and not just the last mtr output.
I'd write the script just a bit differently; piping all of the mtr output straight to awk and letting it do all of the work.
#!/usr/bin/env sh
target=www.google.com
log=/home/rich/mtr.log
date +"%D"_"%T" >>$log
mtr -report -c 5 $target | awk -v logf=$log '
{ print >>logf; } # save all mtr output to log file for history
index( $2, "%" ) > 0 { # you could do /%/ but that might catch more than youd like /packet loss/ would be best if that is in the output
if( max < $2+0 ) # allow for multiple in output; keep largest
max = $2+0; # +0 forces it to be numeric
}
END {
if( max == 0 ) # write to tty the findings of this pass
printf( "no packet loss\n" );
else
printf( "packet loss of %d%%\n", max );
}'
I'd also use Kshell or bash over sh, unless for some reason you're required to use sh. #!/usr/bin/env ksh at the top should be all you need to switch.