编辑以适应评论
@echo off
setlocal enableextensions enabledelayedexpansion
rem Get address from command line
set "address=%~1"
if not defined address set "address=127.0.0.1"
rem Configure levels and colors
rem The format is initialValue:color in value descending format
set "levels=9000:4f 500:5f 130:e0 0:a0"
rem infinite loop
for /l %%i in () do (
rem retrieve information from ping command
set "rtt=9999"
set "ttl=?"
for /f "tokens=3,4 delims==^<" %%a in (
'ping -n 1 "%address%" ^| find "TTL="'
) do for /f "tokens=1 delims=m" %%c in ("%%a") do (
set /a "rtt=%%c"
set "ttl=%%b"
)
rem retrieve color
set "color="
for %%z in (%levels%) do for /f "tokens=1,2 delims=:" %%a in ("%%z") do (
if not defined color if !rtt! geq %%a set "color=%%b"
)
rem show information
if defined color color !color!
echo(!time! - %address% - rtt[!rtt!] ttl[!ttl!]
rem save to log
for /f "tokens=1-4 delims=.:-/ " %%a in ("!date!") do (
>> "pingLog_%%a%%b%%c%%d.txt" echo(!time! - %address% - rtt[!rtt!] ttl[!ttl!]
)
rem wait and repeat the process
ping -n 3 localhost >nul 2>nul
)
它只是重复一个无限循环检查指示的地址(在此代码中从命令行读取)。
在每次迭代中,从 ping 命令确定当前的 rtt,根据 rtt 选择的颜色以及随着颜色变化而回显到控制台的信息。
要获得 rtt,需要执行 ping 操作。如果主机处于活动状态,它将是TTL=
输出中的字符串。如果找到该行,则使用字符=<
作为分隔符对其进行标记,以获取第三个标记(rtt 所在的位置),然后使用m
fromms
分隔 rtt 的数值。
随着 rtt 时间,级别列表中的值(对级别:颜色)被迭代。对于每个值,级别和颜色是分开的,并根据 rtt 测试级别。如果 rtt 大于或等于级别,我们已经找到了合适的颜色。
颜色改变,打印信息,代码在开始新的迭代之前等待