每5秒ping远程计算机的批处理脚本?

时间:2014-03-05 12:50:58

标签: loops batch-file ping repeat

我正在尝试创建一个脚本,每隔5或10秒对我的远程计算机进行ping操作,看看它是否在重新启动后重新联机。

我有这个代码似乎可以工作,但垃圾邮件就像疯了一样,我只需要每5秒检查一次。

如果它在成功连接后停止循环,那么它将获得奖励。

@echo off
:loop
echo Checking connection...

ping -n 1 xx.xxx.xxx.xx >nul
if errorlevel 1 (
  cls
  echo Computer is offline
  goto loop>nul

)

cls
echo Computer is online
  goto loop>nul

4 个答案:

答案 0 :(得分:1)

@echo off
:loop    
    ping -n 1 -w 500 -4 xx.xx.xx.xx 2>nul|find "TTL=" >nul||(echo offline & ping -w 1000 -n 6 localhost >nul & goto loop)
    echo online

答案 1 :(得分:1)

我想,以下是您问题的最佳解决方案。尝试这个脚本,让我知道是否有效。

#!/bin/ksh
pingSuccess=0
while [ 1 -eq 1 ]
do
        ping -c 1 $1 >/dev/null 2>&1 && pingSuccess=1
        [ ${pingSuccess} -eq 1 ] && echo "got the successful ping. " && break
        echo "ping failed. sleeping for 5 secs" && sleep 5
done
echo "exitting.."; exit 0

答案 2 :(得分:0)

没有测试,但这应该有效:

@echo off
SET IP=xxx.xxx.xxx.xxx
SET TIMEOUT=5000
:loop
echo Checking connection...

ping -n 1 %IP% >nul
if errorlevel not 0 (
  cls
  echo Computer at %IP% is offline, waiting %TIMEOUT%ms before retrying
  ping -n 1 1.0.0.1 -w %TIMEOUT% >nul
  goto loop>nul

)
echo Computer at %IP% is online

你可以改变

SET IP=xxx.xxx.xxx.xxx

为:

SET IP=%1

并将IP地址作为批处理文件的参数。

此外,确保无法访问IP 1.0.0.1,它用于创建超时。

答案 3 :(得分:0)

我将如何做到这一点。

@echo off
setlocal

:pingagain
set /a inc+=5
set "ip=xx.xx.xx.xx"
Call :IsPingable %ip% && (
Echo %ip% is online
) || (
Echo %ip% is not online yet. 
ping  127.0.0.1 -n 1 -w 5000>nul
goto :pingagain)
exit /b   

:IsPingable <comp>
ping -n 1 -w 3000 -4 -l 8 "%~1" | Find "TTL=">nul  
exit /b