【问题标题】:Wait for network connection before executing a batch file在执行批处理文件之前等待网络连接
【发布时间】:2015-03-14 14:33:28
【问题描述】:

我有一个 bat 可以在登录 Windows 时运行 python 脚本。

start C:\python34\pythonw.exe D:\myscript.py

myscript.py 需要一些互联网活动,有时因为登录 Windows 后没有立即激活互联网连接而无法正常执行。

如何确保 myscript 仅在 Internet 连接建立后运行?

【问题讨论】:

    标签: batch-file


    【解决方案1】:

    只需 ping 一个服务器,例如 www.google.com 然后你只需要像这样检查错误级别的答案:

    ping www.google.com -n 1 -w 1000
    if errorlevel 0 start C:\python34\pythonw.exe D:\myscript.py
    if errorlevel 1 echo No network
    

    编辑: 添加了几行代码。

    还有一个编辑: 一个更好的方法是这样的:

    :ping
    ping 1.2.3.4 -n 1 -w 1000 > nul
    set target=www.google.com
    ping %target% -n 1 | find "TTL="
    if errorlevel==1 goto ping
    start C:\python34\pythonw.exe D:\myscript.py
    

    第一次 ping 会增加 1 秒(1000 毫秒)的延迟,因此我们不会超载。

    【讨论】:

    • 您的答案是在没有网络连接时打印“No network”,但不能确保 myscript 仅在网络连接下运行。
    • "destination not reachable" 也会给出错误级别 0(误报)。
    • 那一定是因为你得到了回应,但不是肯定的。我有一个脚本来检查家里的实际反应。我会尽量记住发布它:)
    【解决方案2】:
    @echo off
    set target=www.google.com
    echo Waiting for connection..
    :ping
    <nul set /p strTemp=.
    timeout 2 > NUL
    ping %target% -n 1 | find "TTL="
    if errorlevel==1 goto ping
    echo.
    echo Connected
    REM start somthing
    REM start C:\_soft\putty.exe
    

    【讨论】:

    • 这可能是一个正确的答案,但对您的代码提供额外的解释会很有用,以便开发人员能够理解您的推理。这对于可能不熟悉语法的新开发人员特别有用。此外,它可以帮助减少对后续问题的需求。您介意用更多详细信息更新您的评论吗?
    【解决方案3】:

    这对我有用,对你也有帮助!

    
    @ECHO OFF
    :loop
    PING google.com | FIND "time=" > NUL
    echo waiting.....
    IF ERRORLEVEL 1 goto loop 
    
    ECHO You have active connection to the Internet
    
    REM you can add your scripts to run after internet connection success
    
    pause
    

    现在我尝试在bat中显示为正在加载,上面的代码将打印等待....直到连接成功

    【讨论】:

    • 这段代码声称我没有互联网连接(ping 报告Antwort von 172.217.18.100: Bytes=32 Zeit=12ms TTL=121,(没有字符串time=))。这就是为什么其他答案搜索字符串TTL= 的原因,该字符串与语言无关,并且是ping 唯一国际可靠的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2014-01-12
    相关资源
    最近更新 更多