Linux: How to create a ping report with a simple script

Recently i had the following request, there was a need for a solution that would read all entries in /etc/hosts and ping each host and…

Linux: How to create a ping report with a simple script
Photo by Lisa Keffer on Unsplash

Recently i had the following request, there was a need for a solution that would read all entries in /etc/hosts and ping each host and create a report of this

host,pkt_loss,latency

At first it doesnt sounds complicated but it has a catch! since there are a lot of hosts in /etc/hosts it will take a lot of time to complete the report, but here comes the power of xargs to parallelize tasks! lets see how we can do this!

Creating the script

#!/bin/bash 
 
echo "host,pkt_loss,time" > /tmp/pinger.csv 
cat /etc/hosts | grep -i [a-z,A-Z] | grep -v '#' | tr -s " " | cut -d " " -f2 > /tmp/hosts.csv 
cat /tmp/hosts.csv | xargs -n 1 -P 8 -I {} bash -c "ping -w4 -c 4 {} | grep -i statistics -A1 | paste -d ' ' - - | sed 's/, +[0-9] errors//g' | cut -d ' ' -f2,11,15 | tr -d '%' | sed 's/ms//' | tr -s ' ' ','>>/tmp/pinger.csv"

Lets break down the script line by line

This line empties the file from previous run and creates the csv headers

echo "host,pkt_loss,time" > /tmp/pinger.csv

The following line gets the host names from the /etc/hosts file and save them to /tmp/hosts.csv you need this line in order not to filter out commented or empty lines

cat /etc/hosts | grep -i [a-z,A-Z] | grep -v '#' | tr -s " " | cut -d " " -f2 > /tmp/hosts.csv

Now this line is the heart of the script which does all the hard work!

cat /tmp/hosts.csv | xargs -n 1 -P 8 -I {} bash -c "ping -w4 -c 4 {} | grep -i statistics -A1 | paste -d ' ' - - | sed 's/, +[0-9] errors//g' | cut -d ' ' -f2,11,15 | tr -d '%' | sed 's/ms//' | tr -s ' ' ','>>/tmp/pinger.csv"
  • xargs reads each host from stdin and creates batches to 8 ping hosts each ping job has a timeout of 4 packets and a timeout of 4 seconds
  • grep -i statistics is part of the parsing, it starts parsing from line contains word ‘statistics’ and the next line, then paste command merges those two lines to one
  • sed deletes if exists the pattern , [digit] errors and cut gets only columns 2,11,15
  • tr and the rest of the oneliner does some formating like deleting characters and not needed text and saves output to /tmp/pinger.csv

The final output of the csv would be something like this

host,pkt_loss,time 
server01,100,0 
server02,0,3073 
server03,100,3067 
server04,25,3065
  • host is the hostname
  • pkt_loss is the percentage of lost packets
  • time is the total latency

Conclusion

This small report might be useful to be parsed from other tools and create plots and alerts, in my case this will be used to inserted to an influxdb which in turn grafana will use to create visualizations of this ping report!