脚本/批处理以常规间隔Ping服务器&记录慢响应时间

时间:2013-09-13 17:22:32

标签: networking batch-file ping

我的网络连接出现问题,并希望能够定期(例如1-5s)ping远程服务器并记录那些花费超过规定时间(比如说500ms)的请求一个日志文件,带有时间戳。有没有办法通过脚本或批处理文件或可以在我的客户端计算机上连续运行的东西来执行此操作?

2 个答案:

答案 0 :(得分:1)

如果你使用ping命令,你就有时间回答:

C:\Users\Private\TEST>ping google.com

Pinging google.com [173.194.70.138] with 32 bytes of data:
Reply from 173.194.70.138: bytes=32 time=25ms TTL=50
Reply from 173.194.70.138: bytes=32 time=25ms TTL=50
Reply from 173.194.70.138: bytes=32 time=24ms TTL=50
Reply from 173.194.70.138: bytes=32 time=24ms TTL=50

Ping statistics for 173.194.70.138:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 24ms, Maximum = 25ms, Average = 24ms

只需使用for /f循环获取时间,将其与500(if %PingTime% gtr 500)进行比较,并将带有时间戳的抓取时间(例如%date%-%time%)写入日志文件。在goto循环中设置命令以重复它。

答案 1 :(得分:1)

这是我能够创建的最终批次来解决问题。该批次不考虑对ping有“请求超时”响应的情况。由于缓慢的响应时间总是在大块时间内发生,因此只需捕获慢的ping响应时间就足够了。

您可以根据具体情况简单修改“serverName”和“maxPingTime”变量。

@echo OFF
setlocal enabledelayedexpansion

set serverName=myServerName
set maxPingTime=120

:loop 


REM // execute a ping command, iterate over each line returned, & note the 5th string (space-delimited)
for /f "tokens=5" %%a in ('ping -n 1 %myServerName%') do  (

  REM // store the 5th string in a variable
  set pingToken=%%a

  REM // we only want the line for which the first 4 characters of the 5th string equals "time" (i.e. "time=120ms")
  if "!pingToken:~0,4!" equ "time" (

    REM // strip off the last 2 letters of the string (i.e. "ms")
    set tokenWithoutUnits=!pingToken:~0,-2!

    REM // strip off the first 5 letters of the string (i.e. "time=")
    set pingTime=!tokenWithoutUnits:~5,3!

    REM // Compare the ping time to some maximum value of millisseconds
    if !pingTime! gtr !maxPingTime!  (

      REM // Write the date, time, and ping time (in ms) to a text file
      echo %DATE%-%TIME% !pingTime! >> slowpings.txt

    )   

    REM // Wait for 4 seconds before issuing another ping
    ping 1.1.1.1 -n 5 > nul
  )


)

REM // jump back to the beginning of the loop
GOTO :loop