A simple cmd script that can perform an action if a ping is successful. You can change lines 15 and 18 to do whatever you like.
In line 4, I use ping -n 1 %1 - this has several implications. First, the %1 is whatever argument you provide to the script. So if the script were called pingcheck and you executed pingcheck 192.168.0.1, then the script will ping 192.168.0.1 and only get to :pingsuccess if it sees one or more instances of the string "Reply from 192.168.0.1" in the output from ping.
Second, you can change the -n parameter. If you're worried a single ping may not get through, use ping -n 4 and the script will still get to :pingsuccess if even one ping gets through.
Third, ping's reply strings always use the IP address, not the name. So this script wouldn't work if you invoked it with, say, pingcheck www.yahoo.com - since there would never be output saying Reply from www.yahoo.com. You need to provide a dotted-quad IP address as the argument. This is not optimal I admit! But since I have not mapped out every possible reply message that ping might return, it's the best I could do. If you know where full docs of all possible ping responses exist, let me know! Or maybe the errorlevels ping returns.
@echo off
setlocal
set replycount=0
for /f %%a in ('ping -n 1 %1 ^|findstr /c:"Reply from %1"') do call :incrementcounter
if %replycount% gtr 0 (call :pingsuccess) else call :pingfail
echo Done.
endlocal
:incrementcounter
set /a replycount= %replycount% + 1
goto :eof
:pingsuccess
echo Successful ping!
goto :eof
:pingfail
echo Failed ping.
goto :eof
Here's what the ouput looks like:
C:\>pingcheck 192.168.244.244 <--a purposely bad address Failed ping. Done.
C:\>pingcheck 192.168.0.1 <-- a known good address Successful ping! Done. |
Hey! Nice web site. You and I are solving similar sysadmin problems.
You can simplify your ping test and use actual host names by using the logical_or "||" or logical_and "&&" symbols.
ping -n 1 %1 > nul || @goto pingfail
goto ping success
Focus passes through the || only if ping fails (ie errorlevel 1).
Steven Wettberg's Alive.exe program returns errorlevels for several different types of failures: ttl expired, bad destination, etc. So if you're testing for more types of failures, Alive.exe might be a better choice than ping.exe - ymmv.
Alive.exe might be a good candidate for your quuxutils collection.
Rob W.
Rob, thanks for mentioning the || operator. I don't use it enough, I admit.
But it doesn't really fit well in this script, because I often change the -n argument to 2 or more. In that way I can send multiple pings to the address, but still indicate success (host is up and reachable) if one or more pings get through.