Batch Files - Using ping to test network connectivity

前端 未结 8 1045
名媛妹妹
名媛妹妹 2021-01-04 17:17

Using a batch file would it be possible to do something like:

ping google.com

if return success do ECHO You are connected to the internet

else return

相关标签:
8条回答
  • 2021-01-04 17:36

    Here's a script that will repeatedly check, and write the time (from system clock) and "internet offline" to a log file at C:\Internet.txt each time the internet goes offline. Unfortunately the latest line in the log file will appear at the end - I don't know how to make it appear at the top ;)

    BTW: I set the wait time (-w) to 20 seconds, because I was using a 3G dongle (with 2G internet) so 20s was often the only way to be sure if the internet was really down or something else was the problem... Feel free to change it to 5000 for 5s, or delete "-w 20000" altogether to leave it at default.

    @echo off
    
    :START
    
    ping -n 4 4.2.2.2 -w 20000 >nul
    
    if %errorlevel% == 1 (
      echo Internet offline >> C:\Internet.txt
      Time /t >> C:\Internet.txt
    )
    
    Timeout /t 30
    @set errorlevel = 0
    
    GOTO START
    
    0 讨论(0)
  • 2021-01-04 17:48
    @echo off
    :loop
    ping www.google.com -n 1 -w 5000 >NUL
    if errorlevel 1 echo Not connected
    goto Loop
    
    0 讨论(0)
  • Here is a script to help you start with it:

    http://www.techimo.com/forum/networking-internet/73769-handy-batch-file-check-network-connectivity.html

    NOTE: If your system is not in English, you will have to modify the lines in the script where find command is being used to filter Reply from from the ping's output to the corresponding string in the system's language.

    0 讨论(0)
  • 2021-01-04 17:54

    Based on the answer from @CShulz, here's a script that'll print "Not connected" only when there's no connection, else it'll silently loop through the test every 30 seconds. First ping tests for connectivity & prints an error message if there's a problem. The second ping adds a 30 second wait by pinging the localhost.

    @echo off
    :loop
    ping www.google.com -n 1 -w 5000 > nul
    if errorlevel 1 echo Not connected
    ping -n 30 127.0.0.1 > nul
    goto loop
    
    0 讨论(0)
  • 2021-01-04 17:54
    echo Testing Internet Connection of google.com
    @echo off
    :loop
    ping google.com -n 1 -w 5000 > nul
    if errorlevel 1 echo %date% - %time% Not connected >> pingtestlog.txt
    ping -n 30 127.0.0.1 > nul
    goto loop
    
    0 讨论(0)
  • 2021-01-04 17:55
    @echo off
    echo Checking connection
    ping -n 1 www.google.com >nul
    if errorlevel 1 (
      cls
      echo Failed
      pause>nul
      exit
    )
    
    cls
    echo Success!
    pause>nul
    exit
    
    0 讨论(0)
提交回复
热议问题