使用 txt 文件中列出的名称字符串对 IP 列表进行 Ping,并且必须使用批处理

使用 txt 文件中列出的名称字符串对 IP 列表进行 Ping,并且必须使用批处理

我想 ping 一个 IP 列表,并在其旁边输入一串文本。文本将包含多个单词并带有数字。所有 IP 均以 10.xxx 开头

这是我正在研究的一个脚本,但它试图解析我输入的 IP。我猜如果我把主机名放进去,它就会起作用。也许我应该把它放进去以防万一。

@echo off
setlocal enabledelayedexpansion

set OUTPUT_FILE=result.txt
>nul copy nul %OUTPUT_FILE%
for /f %%i in (testservers.txt) do (
    set SERVER_ADDRESS=ADDRESS N/A
    for /f "tokens=1,2,3" %%x in ('ping -n 1 %%i ^&^& echo SERVER_IS_UP') do (
        if %%x==Pinging set SERVER_ADDRESS=%%y
        if %%x==Reply set SERVER_ADDRESS=%%z
        if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
    )
    echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! >>%OUTPUT_FILE%
)

我真正想要的是有一个像“这是服务器 XYZ”这样的文本字符串连接到行尾结果.txt文件。

所以我的测试服务器.txt文件将如下所示:

10.0.0.1 This is the Server ABC.
10.0.0.2 This is the Server DEF.
hostname1 This is the Server LMN.
hostname2 This is the Server XYZ.

当我现在运行它时,它会将这样的结果吐到结果.txt文件。

10.0.0.1 [10.0.0.1] is UP
10.0.0.1 [10.0.0.2] is UP
hostname1 [10.0.0.3] is UP
hostname2 [10.0.0.4] is UP

那么 result.txt 文件将如下所示:

10.0.0.1 [10.0.0.1] is UP This is the Server ABC.
10.0.0.2 [10.0.0.2] This is the Server DEF.
hostname1 [10.0.0.3] This is the Server LMN.
hostname2 [10.0.0.4] This is the Server XYZ.

希望我提供了足够的信息。如果没有,请告诉我。

答案1

由于您使用FOR /F循环读取文本文档内容测试服务器.txt然后您只需添加“ TOKENS=1,*”,第一个标记将是每行的服务器名称或 IP 地址,下一个标记将是之后每行的剩余部分。

这意味着您可以利用循环的下一个标记FOR /F来获取第一个标记之后的每一行的剩余部分,并将其附加到的ECHO%OUTPUT_FILE%

测试服务器.txt

在此处输入图片描述


示例脚本

@echo off
setlocal enabledelayedexpansion

set OUTPUT_FILE=result.txt
>nul copy nul %OUTPUT_FILE%
for /f "tokens=1,*" %%i in (testservers.txt) do (
    set SERVER_ADDRESS=ADDRESS N/A
    for /f "tokens=1,2,3" %%x in ('ping -n 1 %%i ^&^& echo SERVER_IS_UP') do (
        if %%x==Pinging set SERVER_ADDRESS=%%y
        if %%x==Reply set SERVER_ADDRESS=%%z
        if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
    )
    echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! %%j >>%OUTPUT_FILE%
)

输出结果

10.0.0.1 [10.0.0.1] is DOWN This is the Server ABC. 
10.0.0.2 [10.0.0.2] is DOWN This is the Server DEF. 
hostname1 [<IP Address>] is UP This is the Server LMN. 
hostname2 [<IP Address>] is UP This is the Server XYZ. 

更多资源

  • 为/F

  • FOR /?

        tokens=x,y,m-n  - specifies which tokens from each line are to
                          be passed to the for body for each iteration.
                          This will cause additional variable names to
                          be allocated.  The m-n form is a range,
                          specifying the mth through the nth tokens.  If
                          the last character in the tokens= string is an
                          asterisk, then an additional variable is
                          allocated and receives the remaining text on
                          the line after the last token parsed.
    

相关内容