1

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.

  • 2
    Loop 5 times, adding the status codes ($?). If the total is > 0, then you have at least 1 failure in your 5 tests. If == 5, you know it failed 5 times. – Nic3500 Feb 08 '23 at 18:30
  • 2
    BTW, in general, don't use `foo; if [ $? -eq 0 ]; then` -- instead, just use `if foo; then`. See [Why is testing `$?` to see if a command succeeded or not an anti-pattern?](https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern) – Charles Duffy Feb 08 '23 at 18:44
  • 2
    Also, you probably want to be _appending_ to your log file, not truncating it. And what's the purpose of `variable=$(echo "something")` when you could use `variable="something"`? – Charles Duffy Feb 08 '23 at 18:45
  • 2
    Try using `ping -c 5 ...`. It should return good status unless all 5 ping attempts fail. – pjh Feb 08 '23 at 18:52
  • 2
    [Shellcheck](https://www.shellcheck.net/) identifies several problems with the code in the question. The report includes links to more information about the problems and how to fix them. It's a good idea to run [Shellcheck](https://www.shellcheck.net/) on all new and modified shell code. – pjh Feb 08 '23 at 18:55

1 Answers1

1

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.

Maximilian Ballard
  • 815
  • 1
  • 11
  • 19