Pergunta

I want to ping an IP address every 5 seconds.

If the ping fails, write the date and time to a file.

Here is my non-working attempt... the loop works as intended, but I can't get it to write to a file if the ping fails.

@ECHO OFF
set IPADDRESS=172.30.1.36
set INTERVAL=5
:PINGINTERVAL

ping %IPADDRESS% -n 1
if errorlevel 1 echo %date% %time% >> failurelog.txt

timeout %INTERVAL%
GOTO PINGINTERVAL
Foi útil?

Solução

In ipv4, ping command only raises errorlevel if there are packets lost. But in you are pinging a machine in your same subnet, you get no packets lost.

The easier way to test for ping success is to test for the "TTL=" string in the output of the ping

ping -n 1 %ipaddress% | find "TTL=" > nul
if errorlevel 1 echo %date% %time% >> failurelog.txt

Outras dicas

This will ping with no intervals until connection is lost. When it does, it records the failed ping "time and date" on a file to the Desktop. Then, it tries to ping again in 1 second and so on until connection is reestablished, at which point it stops, until next ping is missed. Copy code, change the "set IPADDRESS", and save as a .bat file. Good luck

@ECHO OFF
set IPADDRESS=172.16.100.30
set INTERVAL=1
:PINGINTERVAL

ping -n 1 %ipaddress% | find "TTL=" >nul

if errorlevel 1 (

echo %date% %time% >> C:\Users\%username%\Desktop\failping.txt
echo %date% %time%
timeout %INTERVAL% >nul
)

GOTO PINGINTERVAL
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top