1

how to display only status of ping result like this- here is "My serverx is...fixed only change the online / offline status.

** My server1 is .... online

** My server2 is .... online

** My server3 is .... offline

i was try to this..but fail

@echo off
ping My server1|find "Reply from " >NUL
IF NOT ERRORLEVEL 1 echo Success
IF     ERRORLEVEL 1 echo Fail

ping My server2|find "Reply from " >NUL
IF NOT ERRORLEVEL 1 echo Success
IF     ERRORLEVEL 1 echo Fail

ping My server3|find "Reply from " >NUL
IF NOT ERRORLEVEL 1 echo Success
IF     ERRORLEVEL 1 echo Fail

echo My server1 is ....%ver%
echo My server2 is ....%ver%
echo My server3 is ....%ver%

how to set variable here to do like this.

thanks.

aphoria
  • 19,796
  • 7
  • 64
  • 73
Sunath
  • 11
  • 3

1 Answers1

0

You can do it with one line per server this way:

ping -n 1 server1 | find "TTL=" >NUL && echo server1 is online. || echo server1 is offline.
ping -n 1 server2 | find "TTL=" >NUL && echo server2 is online. || echo server2 is offline.
ping -n 1 server3 | find "TTL=" >NUL && echo server3 is online. || echo server3 is offline.

It's basically shorthand for

ping -n 1 server1 | find "TTL=" >NUL
if not errorlevel 1 (
    echo server1 is online.
) else (
    echo server1 is offline.
)

... etc. If your hosts you're pinging are sequential, you could use perhaps even less code by employing a for /L loop or similar, something like this:

for /L %%I in (1,1,254) do (
    ping -n 1 192.168.0.%%I | find "TTL=" >NUL && echo 192.168.0.%%I is online. || echo 192.168.0.%%I is offline.
)

Type help for in a cmd console for more information about for /L.

Edit: See MC ND's comment immediately below regarding trusting ping to set the errorlevel. Even the example in the question above looking for Reply from can result in a false success. Using find "TTL=" to set errorlevel is more reliable.

For more info on conditional execution, read this.

rojo
  • 24,000
  • 5
  • 55
  • 101
  • 1
    errorlevel is not a reliable way to check for ping sucess. In ipv4, errorlevel is set if any packet is lost, and pinging an inactive machine on the same vlan will result in a non reachable machine with no packet lost and no errorlevel. And the behaviour is different for ipv6 (more [here](http://stackoverflow.com/a/23720500/2861476)) – MC ND Dec 02 '14 at 20:48
  • I see. I just pinged a non-existent host within my subnet and got "Reply from (my local machine): Destination host unreachable", but `%ERRORLEVEL%` was 0. I like your idea of watching for `TTL=`. – rojo Dec 02 '14 at 21:03
  • @MCND as a matter of interest, if what you're checking is a group of web servers and you'd like a script to check whether the HTTP service on each returns a status of "200 OK", [this question](http://stackoverflow.com/q/15395490/1683264) has a script that does that. Pretty clever! – rojo Dec 02 '14 at 21:21
  • Hi rojo, i appreciate your answer and try to make it. – Sunath Dec 03 '14 at 04:08