0

How can I construct a command to ping a host every minute or something, then run a command when it doesn't time out (when the pinged host comes online)?

Basically I want the following pseudocode:

bool ping = pingHost();
while (ping = false) {
    //try again
    ping = pingHost();
}
runCommand("whatever");

Preferably, answers would include instructions for UNIX-like systems (using bash, etc) as well as Windows systems (cmd, PowerShell or Cygwin all work).

2
  • 1
    What have you researched and/or tried? Did you try a search for this?
    – CharlieRB
    May 17, 2013 at 20:07
  • @CharlieRB ah, I didn't think of that. I just searched for "run command on ping success" or something, which returned much less useful results.
    – strugee
    May 18, 2013 at 1:02

1 Answer 1

4

First of all please let me point out that you would probably want to use a more complete monitoring software like Nagios for this.

For the basic scripting solution, on Linux I would use Bash for this:

#!/bin/bash
ping -c 1 yourhost.com
if [ $? -eq 0 ]; then
    your_command
fi

Windows is quite similar actually. Put this into a .bat file:

ping -n 1 yourhost.com
IF %ERRORLEVEL%==0 (
    your_command
)

Explanation: the ping command returns an exit code on both operating systems. On Linux (Bash) you have the $? variable to get this exit code, on Windows it's %errorlevel%. When the ping is successful, the exit code on both operating systems is 0, otherwise it's 1. This value can be used to run your command conditionally.

Adding the loop:

On Linux:

#!/bin/bash
result=1
while [ $result -neq 0 ]; do
    ping -c 1 yourhost.com
    result=$?
done

On Windows the same would be:

:loop
ping -n 1 yourhost.com
IF NOT %ERRORLEVEL%==0 (
    goto loop
)
your_command

Remark: If you want to use it every time the host is online, you can use the crontab on Linux or the Task Scheduler on Windows. If you want to run it every time the host comes online, you need a proper monitoring software.

1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .