在 windows 命令行上检查主机可达性

Checking host reachability on windows command line

如果主机是否可达,我如何检查批处理文件?问题是 ping returns 0 不仅成功,而且 Destination host unreachable 错误:

C:\>ping 192.168.1.1 -n 1

Pinging 192.168.1.1 with 32 bytes of data:
Reply from 192.168.1.1: bytes=32 time=3ms TTL=64

Ping statistics for 192.168.1.1:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 3ms, Maximum = 3ms, Average = 3ms

C:\>echo %errorlevel%
0

C:\>ping 192.168.1.105 -n 1

Pinging 192.168.1.105 with 32 bytes of data:
Reply from 192.168.1.102: Destination host unreachable.

Ping statistics for 192.168.1.105:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),

C:\>echo %errorlevel%
0

有什么方法可以使用 ping 或任何其他内置的 Windows 工具吗?如果可能的话,我宁愿不安装任何东西...

做这样的事情:

PING 192.168.1.1 -n 1 | FIND /I "Reply from "

然后你可以查看errorlevel

编辑:为了适应“目标主机无法访问错误”,您可以这样做:

PING 192.168.1.1 -n 1 | FIND /I /V "unreachable" | FIND /I "Reply from "

我认为 tracert 是你 need.Sets errorlevel on 1 如果找不到 host.And 应该使用与 ping 相同的端口。-h 2 是为了减少等待时间,因为完整不需要路由。

tracert -h 2 somehost.com >nul 2>nul && (
  echo reachable host
) || (
  echo unreachable host
)

编辑:要在括号中打印正确的错误级别,您需要延迟 expansion.Here 的更高级示例:

@echo off

setlocal enableDelayedExpansion

echo checking google.com
tracert -h 1 google.com >nul 2>nul && (
  echo reachable host
  echo !errorlevel!
  rem prevent execution of negative condition
  color 22
) || (
  echo unreachable host 
  echo !errorlevel!
)


echo checking asdasdjjakskwkdhasdasd
tracert -h 1 asdasdjjakskwkdhasdasd >nul 2>nul && (
  echo reachable host#
  echo !errorlevel!
   rem prevent execution of negative condition
   color
) || (
  echo unreachable host#
  echo !errorlevel!
)

下一个代码片段应该可以工作:

set "_ip=localhost"
set "_ip=192.168.1.1"
ping %_ip% -n 1 -4 | find /i "TTL=">nul
if errorlevel 1 (
    echo ping %_ip% failure
) else ( 
    echo ping %_ip% success
)
  • -4 强制使用 IPv4(例如 ping localhost 回复 IPv6 没有 TTL= 输出)
  • | find /i "TTL=" 作为 find 命令引发 errorlevel well
  • >nul 抑制不需要的输出