batch-file - 更改 ping 错误消息
问题描述
我正在制作一个简单的批处理脚本来 ping 主机并检查它们的连接。这是我的代码:
@ECHO OFF
@powershell -ExecutionPolicy UnRestricted -Command "(Add-Type -memberDefinition \"[DllImport(\"\"user32.dll\"\")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x,int y,int cx, int xy, uint flagsw);\" -name \"Win32SetWindowPos\" -passThru )::SetWindowPos((Add-Type -memberDefinition \"[DllImport(\"\"Kernel32.dll\"\")] public static extern IntPtr GetConsoleWindow();\" -name \"Win32GetConsoleWindow\" -passThru )::GetConsoleWindow(),-1,0,0,0,0,67)"
title Ping tool
mode con: cols=50 lines=25
:PING
cls & set /p address= [*] Host to ping:
@echo [*] Started pinging at: %time%
title Pinging %address%
if %ERRORLEVEL% == 1 echo Host didn't respond.
ping %address% -t & echo. & pause. & goto :PING
我正在努力做到这一点,以便当我收到错误代码(请求超时)时,它会打印“主机没有响应”而不是通常的。但是它不起作用。
通常我的 ping 会输出这个:
[*] Host to ping: 8.8.8.8
[*] Started pinging at: 13:44:29.05
Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=28ms TTL=52
Reply from 8.8.8.8: bytes=32 time=16ms TTL=52
Request timed out.
Request timed out.
等等
但我希望它看起来像这样:
[*] Host to ping: 8.8.8.8
[*] Started pinging at: 13:44:29.05
Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=28ms TTL=52
Reply from 8.8.8.8: bytes=32 time=16ms TTL=52
Host didn't respond.
Host didn't respond.
我将如何继续这样做?
PS 脚本的第二行是我在此处找到的命令,它使 CMD 窗口始终位于顶部。很有用!
解决方案
您无法在命令仍在运行时拦截它的输出,因此ping -t
对您不起作用。您需要ping -n 1
循环,因此您可以对每个 ping 包做出反应:
:loop
ping -n 1 www.google.com | find "TTL=" || echo Host didn't respond.
goto :loop
不要忘记实施某种“打破循环”
注意:这在您的内部网络中失败,因为ping
响应Reply from <localhost>: Destination host unreachable.
被视为“成功”,因为有一个答案(只是不是来自目的地)。
推荐阅读
- database - 在终端上运行 mongod 命令时 MongoDB 中止
- reactjs - 如何在 reactjs 中设置引导程序以响应?
- sql - 计算日期差和返回天数
- google-cloud-logging - 日志保留的增加是否具有追溯力?
- scala - 在 Scala 中读取大型 csv 文件的功能样式
- sql - SQL:选择3个值并计算它们不同的次数
- google-apps-script - 自动 .XLS 到 Google 表格转换器不起作用
- python - 不会返回空白日期行的 Pandas 函数
- optaplanner - 严重过度约束调度的策略
- ios - ionic 5:相机 getPhoto 承诺无结果