通过服务器排序并确定最快 ping 的简化方法

Streamlined way to sort thru servers and determine the fastest ping

我正在尝试从网络上的许多服务器中确定最快的 ping 速率。服务器的数量可能多达几十台。我确实有如下所示的脚本,目前可以通过一些脚本进行排序并且效果很好,但我正在寻找一种更优雅的方法来完成它。服务器列表也可以存储在文本文件中。实际上,服务器名称的文本文件可能更易于维护,因为它们可能会随时间变化。

编辑:如果服务器离线,此脚本也不会处理,所以我可能会不小心将离线服务器列为最快的 ping。

SET SERVER_A=MEDUBNA2
SET SERVER_B=HANSECAD2
SET SERVER_C=MEINWESSFS01
SET SERVER_D=MEAUHWC01

for /f "tokens=2 delims==," %%a in ('ping %SERVER_A% -n 1 -w 1000') do SET MINSERVER_A=%%a
for /f "tokens=2 delims==," %%b in ('ping %SERVER_B% -n 1 -w 1000') do SET MINSERVER_B=%%b
for /f "tokens=2 delims==," %%c in ('ping %SERVER_C% -n 1 -w 1000') do SET MINSERVER_C=%%c
for /f "tokens=2 delims==," %%d in ('ping %SERVER_D% -n 1 -w 1000') do SET MINSERVER_D=%%d

SET MINSERVER_A=%MINSERVER_A:~0,-2%
SET MINSERVER_B=%MINSERVER_B:~0,-2%
SET MINSERVER_C=%MINSERVER_C:~0,-2%
SET MINSERVER_D=%MINSERVER_D:~0,-2%


if %MINSERVER_A% lss %MINSERVER_B% (
    SET FASTESTSERVERGROUP1=%SERVER_A%
    ) else (
    SET FASTESTSERVERGROUP1=%SERVER_B%
)

if %MINSERVER_C% lss %MINSERVER_D% (
    SET FASTESTSERVERGROUP2=%SERVER_C%
    ) else (
    SET FASTESTSERVERGROUP2=%SERVER_D%
)

if %FASTESTSERVERGROUP1% lss %FASTESTSERVERGROUP2% (
    SET FASTESTSERVEROVERALL=%FASTESTSERVERGROUP1%
    ) else (
    SET FASTESTSERVEROVERALL=%FASTESTSERVERGROUP2%
)

echo %SERVER_A%: %MINSERVER_A%
echo %SERVER_B%: %MINSERVER_B%
echo %SERVER_C%: %MINSERVER_C%
echo %SERVER_D%: %MINSERVER_D%

echo Fastest Server Group 1: %FASTESTSERVERGROUP1%
echo Fastest Server Group 2: %FASTESTSERVERGROUP2%


:: Ultimate goal is to determine the fastest server out of the list.
echo Fastest Server Overall: %FASTESTSERVEROVERALL%

您需要做的就是创建几个嵌套的 FOR 命令来读取服务器列表。然后ping服务器。操纵输出,使其只有数字。然后将数字与当前最快的进行比较。

@echo off
setlocal enabledelayedexpansion
set "ms=10000"
set "fastest="
REM Read the server list
FOR /F "delims=" %%G IN (serverlist.txt) DO (
    REM read the ping results
    for /f "tokens=2 delims==," %%H in ('ping %%G -n 1 -w 1000 ^|find /i "minimum"') do (
        REM Manipulate the ping result so that it is only a number
        for /f "delims=m " %%I in ("%%H") do (
            REM Compare the ping result to the current fastest time.
            IF %%I LSS !ms! (
                set "fastest=%%G"
                set "ms=%%I"
            )
        )
    )
)
echo Fastest Server is: %fastest%
pause