Script to monitor internet connection
The internet often drops at work, so to compile a csv report of the outage time and for how long I wrote this script, which maybe of use to someone.
Simply create the script, with execution rights (sudo chmod a+x) and call the script with the first argument as a resource e.g google and the second argument as the output filename e.g ./monitor.sh google.co.uk myFile
Code below:
#!/bin/bash resource=$1 outfile=$2 dwnTmp=".dwnLock"; upTmp=".upLock"; # NEED A RESOURCE if [[ -z "$resource" ]]; then echo "You must define a resource as the first parameter e.g google.co.uk"; exit; fi #### # NEED A FILENAME if [[ -z "$outfile" ]]; then echo "You must define an output file as the second parameter"; exit; fi #### ### REMOVE LOCKS if [ -f "$dwnTmp" ]; then rm $dwnTmp; fi if [ -f "$upTmp" ]; then rm $upTmp; fi ################# echo "Logging connectivity of http://$resource/ to $outfile.csv CTRL+C to exit" # LOOP count=0 while [ 1=1 ]; do let count+=1 time=$(date +"%T") timeSec=$(date +%s) duration=0 # log wget -q --tries=1 --timeout=10 --spider "http://$resource/" if [[ $? -eq 0 ]]; then if [ ! -f "$upTmp" ]; then echo $timeSec > $upTmp; if [ -f "$dwnTmp" ]; then duration=$(($timeSec-`cat $dwnTmp`)) rm $dwnTmp; fi echo -ne CHECK $count: AVAIL '\r' echo "$count,$time,Up after being down for $(($duration / 60)) minutes and $(($duration % 60)) seconds" >> "$outfile.csv" fi else if [ ! -f "$dwnTmp" ]; then echo $timeSec > $dwnTmp; if [ -f "$upTmp" ]; then duration=$(($timeSec-`cat $upTmp`)) rm $upTmp; fi echo -ne CHECK $count: ERROR '\r' echo "$count,$time,Down after being up for $(($duration / 60)) minutes and $(($duration % 60)) seconds" >> "$outfile.csv" fi fi done #####
2,309 views
This entry was posted on Tuesday, April 21st, 2015 at 11:40 am and is filed under Bash. You can follow any responses to this entry through the RSS 2.0 feed.