如何检查是否平批处理文件回应与否 [英] How to check if ping responded or not in a batch file

查看:125
本文介绍了如何检查是否平批处理文件回应与否的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要不断地Ping通服务器,并看到一个消息框,当过它响应即服务器目前下跌。我想通过批处理文件来做到这一点。

I want to continuously ping a server and see a message box when ever it responds i.e. server is currently down. I want to do it through batch file.

我可以显示一个消息框,如下<一说href=\"http://stackoverflow.com/questions/774175/how-can-i-open-a-message-box-in-a-windows-batch-file/774253#774253\">http://stackoverflow.com/questions/774175/how-can-i-open-a-message-box-in-a-windows-batch-file/774253#774253

I can show a message box as said here http://stackoverflow.com/questions/774175/how-can-i-open-a-message-box-in-a-windows-batch-file/774253#774253

和可以通过

ping <servername> -t

但我怎么检查它是否回应与否?

But how do I check if it responded or not?

推荐答案

下面 checklink.cmd 节目是开始的好地方。它依赖于事实,你可以做一个单杆平,而且,如果成功的话,输出将包含行:

The following checklink.cmd program is a good place to start. It relies on the fact that you can do a single-shot ping and that, if successful, the output will contain the line:

Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),

通过提取标记5和7,并检查他们分别为收到1,,可以检测的成功。

@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
:loop
set state=down
for /f "tokens=5,7" %%a in ('ping -n 1 !ipaddr!') do (
    if "x%%a"=="xReceived" if "x%%b"=="x1," set state=up
)
echo.Link is !state!
ping -n 6 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal

与域名(或IP地址),随你想测试一下:

Call it with the name (or IP address) you want to test:

checklink 127.0.0.1
checklink localhost
checklink nosuchaddress

要考虑到,如果你的语言环境不是英语,则必须更换接收与您所在区域相应的关键字,例如 recibidos 西班牙。做一个测试的ping来发现哪些关键字在你的区域使用。

Take into account that, if your locale is not English, you must replace Received with the corresponding keyword in your locale, for example recibidos for Spanish. Do a test ping to discover what keyword is used in your locale.

要仅通知您,当国家的修改的,你可以使用:

To only notify you when the state changes, you can use:

@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
set oldstate=neither
:loop
set state=down
for /f "tokens=5,7" %%a in ('ping -n 1 !ipaddr!') do (
    if "x%%a"=="xReceived" if "x%%b"=="x1," set state=up
)
if not !state!==!oldstate! (
    echo.Link is !state!
    set oldstate=!state!
)
ping -n 2 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal


不过,由于在加布评论指出的那样,你可以使用 ERRORLEVEL 所以上面第二个脚本相当于变为:


However, as Gabe points out in a comment, you can just use ERRORLEVEL so the equivalent of that second script above becomes:

@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
set oldstate=neither
:loop
set state=up
ping -n 1 !ipaddr! >nul: 2>nul:
if not !errorlevel!==0 set state=down
if not !state!==!oldstate! (
    echo.Link is !state!
    set oldstate=!state!
)
ping -n 2 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal

这篇关于如何检查是否平批处理文件回应与否的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆