Reputation: 1310
Is it possible to retrieve the data output when you type ping in the command line?
Currently, we have existing servers that we check daily by typing ping (IP address) in the command line but only during at the start of the day. We would only be notified if the server is down once the user notifies us. The manual thing to do is to do a continuous ping and do a timely check of whether it was disconnected or not.
I would like to create something that would give out a prompt (while doing a continuous ping in the background) once the command line declares that there's a "request time out", intermittent connection, etc. So that there wouldn't be a need to manually check the status of the connection.
Upvotes: 1
Views: 2313
Reputation: 653
I realize this was asked 2 months ago, but it was never answered. Hopefully this will still be useful to someone. Granted, it's much easier to implement using a "real" programming language, but sometimes you need something that uses only built-in commands.
Configure as needed via environment variables (examples shown). To be polite, you probably want to use much longer timeouts if you don't own the server you're pinging.
@echo off
cls
setlocal enabledelayedexpansion
REM Configuration:
set SERVER=google.com
set TIMEOUT_AFTER_PING_FAIL_SECONDS=5
set TIMEOUT_AFTER_PING_SUCCEED_SECONDS=10
set TIMEOUT_AFTER_LINK_DOWN_SECONDS=15
set DECLARE_LINK_DOWN_FAILS=5
set CONSECUTIVE_FAIL_COUNT=0
:Start
set PING_RESULT=Failure
for /f "delims=" %%X in ('ping /n 1 %SERVER%') do (
set TEMPVAR=%%X
if "Reply from"=="!TEMPVAR:~0,10!" set PING_RESULT=Success
)
goto:!PING_RESULT!
:Success
echo Ping Succeeded
set CONSECUTIVE_FAIL_COUNT=0
call:Sleep %TIMEOUT_AFTER_PING_SUCCEED_SECONDS%
goto:Start
:Failure
set /A CONSECUTIVE_FAIL_COUNT+=1
echo Ping Failed !CONSECUTIVE_FAIL_COUNT! Time(s)
if !CONSECUTIVE_FAIL_COUNT!==%DECLARE_LINK_DOWN_FAILS% (call:LinkDownHandler&goto:Start)
call:Sleep %TIMEOUT_AFTER_PING_FAIL_SECONDS%
goto:Start
:Sleep
REM See http://stackoverflow.com/questions/4317020/windows-batch-sleep
setlocal
set /A ITERATIONS=%1+1
ping -n %ITERATIONS% 127.0.0.1 >nul
goto:eof
:LinkDownHandler
echo Link is Down
set CONSECUTIVE_FAIL_COUNT=0
REM Add additional link-down handler actions here
call:Sleep %TIMEOUT_AFTER_LINK_DOWN_SECONDS%
goto:eof
Upvotes: 1