Windows 命令行 - 根据 Ping 延迟选择服务器

标签 windows batch-file command-line ping

这里的基本前提是有两台服务器有相同的文件。

我正在使用 Windows 命令行脚本并为这些主机中的任何一个打开网络共享。我想让脚本变得“智能”,以便计算出两台服务器之间的延迟并选择延迟最低的主机进行连接。

我想做类似的事情(我知道这段代码不起作用,这是我的概念的一个例子):

PING 192.168.0.1
SET HOST1=%ERRORLEVEL%
PING 192.168.0.2
SET HOST2=%ERRORLEVEL%
IF HOST1 GTR HOST2 GOTO HOST2CONNECT
:HOST1CONNECT
NET USE X: \\HOST1 (etc)
:HOST2CONNECT
NET USE X: \\HOST2 (etc)

这有意义吗?我似乎无法想象一种比较来自两个 PING 测试的数据的方法,我知道在这种情况下,ERRORLEVEL 只是 1 或 0,具体取决于 ping 是否成功,所以它是垃圾,因为它们会都成功了。但我希望你能理解这个概念,并能看到我遗漏了什么。

提前致谢。

最佳答案

@echo off
    setlocal enableextensions disabledelayedexpansion

    rem Initialize variables
    set "selected="
    set "min=99999999"
    set serverList= "bing.com" "duckduckgo.com" "google.es" "google.com"

    echo - Testing -----------------------------

    rem Enumerate the hosts to check
    for %%a in ( %serverList% ) do (

        rem Ping the host and retrieve the average roundtrip
        for /f "tokens=6 delims== " %%r in ('
            ping -n 1 "%%~a" ^| findstr /r /c:"^  .*ms$"
        ') do for /f "delims=ms" %%t in ("%%r") do (
            echo "%%~a" : %%t ms

            rem Determine if the current host has a lower rtt
            rem if %%t geq min or min is already 0, then we have
            rem a division by 0, else a lower rtt has been found
            set /a "1/(min/(%%t+1))" && (
                set "selected=%%~a"
                set "min=%%t"
            )
            rem Of course this can be done with delayed expansion, 
            rem just a question of personal preferences
        )
    ) 2>nul 

    echo(
    echo - Selected ----------------------------
    echo %selected% : %min%

关于Windows 命令行 - 根据 Ping 延迟选择服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44417336/

相关文章:

command-line - 命令行差异实用程序

ruby-on-rails - Ruby 单线故障?

windows - 如何在 Windows 7 上更新 OpenSSL?

php - 如何使用cmd批量多次运行.php脚本?

batch-file - 在批处理脚本中处理八进制变量

powershell - 重新启动后,以管理员模式运行批处理文件

emacs - 将命令行参数转换为 Emacs Lisp 中的列表

python - GridSearchCV 在任何 n_jobs 的窗口上卡住

windows - 为什么 .gitignore.txt 文件在 windows10 中不显示它的名字?

c++ - 在网络第 3 层和第 2 层编程