Samir Ahmadli
Samir Ahmadli

Reputation: 17

bash script for run another script after 5 unreachable ping request to specific ip or website

I need script to run another script after 5 consistently 'unreachable' response from ping to specific ip. But if everything okay do nothing. For example for now I have script running ping command by taking ip addresses from text file which has list of ip or websites. And this script run another telegram message sending script if the ip or website from list is unreachable. But it is not good idea because often there can be just 1 unreacable response but overall the website is working or ip is reachable. Now I need the script which runs telegram message sending script after consistently 5 unreachable response. Not after 1 unreachable response. Here's my script:

date
cat /home/user/list.txt |  while read output
do
    ping -c 1 "$output" > /dev/null
    if [ $? -eq 0 ]; then
    echo "node $output is up"
    else
    message="$(echo "node $output is down")"
    echo "node $output is down" > /home/user/siteDown.log
    telegram-send "$message"
    fi
done    

Thank to all, have a nice days.

Upvotes: 1

Views: 362

Answers (1)

Maximilian Ballard
Maximilian Ballard

Reputation: 996

Try this:

#!/bin/sh

try_ping() {
    i=0
    while [ $((i+=1)) -le 5 ] ; do
        ping -c 1 "${1}" > /dev/null \
            && return 0
        sleep 0.5
    done
    return 1
}

date
while read -r output ; do
    if try_ping "${output}" ; then
       echo "node $output is up"
    else
        echo "node $output is down" >> /home/user/siteDown.log
        telegram-send "node $output is down"
    fi
done </home/user/list.txt

I added a 0.5 second sleep after every ping attempt, but you can adjust that.

Upvotes: 1

Related Questions