Saturday, March 16, 2013

PING goes further than you think

Do you ever need a quick and free method of testing the reliable uptime of a network server? There are lots of paid for bits of software and onine services but if you have a spare Windows box this little DOS command (which you can save as a .BAT file for quick deployment) does a superb job;

cmd.exe /v:on /c "FOR /L %i in (1,0,2) do @ping -n 1 10.100.100.241  | find "Request timed out">NUL && (echo !date! !time! >> PingFail.txt) & ping -n 2 127.0.0.1>NUL"

Make sure that if you cut'n'paste it you edit out any inserted line-breaks.

Inside of our FOR loop is where we really get to the meat. We've basically got 4 steps:

  1. First we see @ping -n 1 10.100.100.241 The @ symbol says to hide the echo of the command to the screen. The switch (-n 1) says to only ping the IP once. And of course 10.100.100.241 is the address we want to ping (at home it's my media machine)
  2. Next we pipe the results of our ping into the FIND command and search for "Request timed out" to see if the ping failed. The last part of that >NUL says to dump the output from this command into NUL, because we don't really need to see it.
  3. Now we get fancy. The && says to only run this command if the previous command succeeded. In other words, if our FIND command finds the text, which means our ping failed, then we run this command. And we've enclosed this command in parenthesis contain it as a single command. We need to use the "cmd.exe /v:on /c" command at the beginning to allow for delayed environment variable expansion; that way our time & date changes each iteration. So %date% and %time% becomes !date! and !time!.
  4. And finally we're redirecting our output to a file called PingFail.txt. We use the >> operator append each new entry rather than overwrite with just >.
  5. And finally we're on to the last step. As mentioned before, the & says to run the next command no matter what has already happened. This command simply pings localhost with (-n 2) which will give us a one-second delay. The first ping happens immediately, and the second ping happens after one second. This slows down our original ping back in step 1 which would otherwise fire off like a machine gun as fast as the FOR loop can go. Lastly, we're redirecting the output with >NUL because we don't care to see it.

No comments: