【问题标题】:Batch Random Pinging(Trying to determine if a ping is successful)Batch Random Pinging(试图确定一个ping是否成功)
【发布时间】:2015-06-06 20:59:32
【问题描述】:

我制作了一个程序,它可以创建随机 IP 并 ping 它们以查看它们是否存在。它使用“>”和“>>”记录输出。我想检查 ping 是否超时以及是否将其从文本文档中排除。到目前为止,这是我的代码:

`@ECHO OFF
:LOOP
 SET /A N1=%RANDOM% * 255 / 32768
 SET /A N2=%RANDOM% * 255 / 32768
 SET /A N3=%RANDOM% * 255 / 32768
 SET /A N4=%RANDOM% * 255 / 32768
 PING %N1%.%N2%.%N3%.%N4%>>"%USERPROFILE%\Desktop\IP.txt"
 GOTO LOOP`

ping 完成后,我希望它记录响应的 IP,而不是超时的 IP。

-提前致谢

【问题讨论】:

标签: batch-file random ip ping


【解决方案1】:
@echo off
    setlocal enableextensions enabledelayedexpansion

    for /l %%a in (0) do (
        set /a  "A=!random! %% 255", ^
                "B=!random! %% 255", ^
                "C=!random! %% 255", ^
                "D=!random! %% 255"

        ping -w 1000 -n 1 "!A!.!B!.!C!.!D!" | find "TTL=" > nul && (
            >>"online.txt" echo !A!.!B!.!C!.!D!
        )
    )

这会创建无限循环(这个for /l %%a in (0) 表示for %%a starting in 0 up to 0 in steps of 0

对于每次迭代,为每个 ip 地址八位字节生成四个随机数。为此,我们使用!random! 变量中的构建生成一个随机数(需要delayed expansion)并使用set /a 命令获得除以255 的余数(在批处理文件中模运算符为%%),进行计算的批处理方式。

生成 ip 后(更多延迟扩展,请参阅之前链接的答案),发送 ping 并检查其输出是否存在 TTL= 字符串 (more information here)。如果此字符串存在,则目标是可访问的,并且地址将附加到文件中。

为了测试该字符串是否出现在ping 命令的输出中,它被传送到find 命令中以搜索指定的字符串。如果字符串找到errorlevel变量设置为0,如果没有找到,errorlevel将设置为1。

使用条件执行运算符&& 检查此值。这意味着如果上一个命令没有将errorlevel 设置为大于 0 的任何值,则执行下一个命令

因此,如果find 命令找到该字符串,errorlevel 将不是 1,并且将执行 echo 命令。这个echo 被重定向到追加到目标文件(>> 是追加重定向)

【讨论】:

    【解决方案2】:
    @echo off
    setlocal EnableDelayedExpansion
    
    rem Set the number of IP's to test
    set num=20
    
    echo Creating and testing %num% IP's
    echo/
    
    for /L %%i in (1,1,%num%) do (
    
       rem Create the random IP
       set /A N1=!random! %% 255, N2=!random! %% 255, N3=!random! %% 255, N4=!random! %% 255
       set "IP=!N1!.!N2!.!N3!.!N4!"
    
       rem Show the IP and leave the cursor after it
       set /P "=%%i- Testing !IP!: " < NUL
    
       rem Test the IP with ping and get just the 3rd word of the 3rd line from ping output
       set "word="
       for /F "skip=2 tokens=3" %%a in ('ping !IP!') do if not defined word set "word=%%a"
    
       rem If that word is not "out", the IP is correct
       if "!word!" neq "out" (
          echo CORRECT
          echo !IP!>> IP.txt
       ) else (
          echo failed...
       )
    
    )
    

    【讨论】:

    • 你能给我解释一下吗?正如我之前所说,我有点新,我不知道其中一些命令。
    猜你喜欢
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 2014-11-23
    相关资源
    最近更新 更多