我试图编写运行ping命令的脚本,从输出中获得平均延迟和包丢失值的%,我尝试了下面的命令,它运行得很好
`ping -n 8 4.4.4.4 > D:\latency.txt
C:\Users\tnt5273>ping 4.2.2.2
Pinging 4.2.2.2 with 32 bytes of data:
Reply from 4.2.2.2: bytes=32 time=253ms TTL=54
Reply from 4.2.2.2: bytes=32 time=242ms TTL=54
Reply from 4.2.2.2: bytes=32 time=252ms TTL=54
Reply from 4.2.2.2: bytes=32 time=248ms TTL=54
Reply from 4.2.2.2: bytes=32 time=253ms TTL=54
Reply from 4.2.2.2: bytes=32 time=242ms TTL=54
Reply from 4.2.2.2: bytes=32 time=252ms TTL=54
Reply from 4.2.2.2: bytes=32 time=248ms TTL=54
Ping statistics for 4.2.2.2:
Packets: Sent = 8, Received = 8, Lost = 0 (**0% loss**),
Approximate round trip times in milli-seconds:
Minimum = 242ms, Maximum = 253ms, Average = **248ms** `然而,这里的挑战是,我想以某种方式从输出中获取数字值(因此可以设置阈值),并以毫秒0248的百分比平均值作为损失值在纯文本文件中发布。
,我不知道如何在windows中这样做,在VB或windows shell脚本中寻找帮助,这可以帮助我实现我的目标
提亚
发布于 2014-11-17 10:09:21
@echo off
setlocal enableextensions disabledelayedexpansion
rem Initialize variables to hold data
set "pct="
set "avg="
rem Run the ping and filter to only read the required lines
rem The first line will contain the loss percentage
rem The second line will contain the average roundtrip
for /f "delims=" %%a in ('
ping -n 8 4.4.4.4 ^| findstr /r /c:"= [0-9]*ms" /c:"([0-9]*%% "
') do if not defined pct (
rem Extract the % loss from the line
for /f "tokens=2 delims=(%%" %%b in ("%%a") do set "pct=%%b"
) else (
rem Retrieve the last element in the line (the average)
for %%b in (%%a) do set "avg=%%b"
)
rem Remove the ms literal from the average
for /f "delims=m" %%a in ("%avg%") do set "avg=%%a"
rem Echo the retrieved values
echo pct=[%pct%]
echo avg=[%avg%]可能比预期的代码要多一点,但在我的系统(西班牙地区)中,丢失百分比显示在一个单独的行中,而文字则不一样。
发布于 2014-11-17 10:00:42
我建议使用而不是ping.exe,因为它返回一个可以轻松获取所需数据的对象。
示例:
$count= 8
$con = Test-Connection 4.2.2.2 -count $count
$average = ($con.ResponseTime | Measure-Object -Average).Average
$lost = $count-($con.count)发布于 2014-11-17 09:55:51
@echo off
for /f "tokens=3 delims=," %%# in ('ping -n 8 173.194.44.131 2^>nul^| findstr /i "loss average"') do (
set "%%#"
)
for /f "tokens=1 delims= " %%a in ("%Average %") do echo average-%%a
for /f "tokens=2 delims=() " %%a in ("%Lost %") do echo loss-%%a在最后两行中,您可以更改输出-- %%a是值损失,平均值是澄清strings.And,可以将结果输出到文件中。
https://stackoverflow.com/questions/26969524
复制相似问题