【问题标题】:Run a simple continuous ping and output the results to csv file运行简单的连续 ping 并将结果输出到 csv 文件
【发布时间】:2018-07-11 18:54:04
【问题描述】:

我正在尝试在 cmd 窗口中的 Windows 10 机器上运行简单的连续 ping,并将时间戳和响应时间输出到 csv 文件中的两列。我不太确定如何做到这一点,因为我对这种类型的编码没有任何经验。任何帮助表示赞赏。

【问题讨论】:

标签: windows csv batch-file cmd ping


【解决方案1】:

这一切都可以用batch 语言完成,相当于您使用cmd 的请求。我在下面编写了一个简单的脚本,它将使用ping 命令和findstr 将响应时间设置为变量。

脚本是连续的,可以从脚本顶部的配置中使用以下设置进行调整:

  • 您要 ping 的地址
  • ping 之间的速度
  • 另存为/更新的文件名

脚本保存文件的方式是使用>> 将输出附加到文件命令。所有脚本内上下文线索都列在:: 中,如果需要,可以从脚本中删除。随意编辑下面的脚本以满足您的需求。如果不知道怎么把这个脚本转成批处理,复制粘贴到记事本,另存为.bat。

@ECHO OFF
@SETLOCAL

::Set the address you wish to ping
SET adress=123.123.12.1

::Set the speed between pings (In seconds)
SET speed=5

::Set the file name to save as - Can include location ex (C:\Users\%username%\Desktop\file.csv)
SET filename=TP.csv

GOTO :ping

:ping
::Ping and extract time= into variable
for /F "tokens=7 delims== " %%G in ('ping -4 -n 1 %adress%^|findstr /i "time="') do set ping=%%G
echo Current ping for %adress%: %ping%

::Set Time stamp
set curTimestamp=%date:~4,2%%date:~7,2%%date:~10,4%_%time:~0,2%%time:~3,2%%time:~6,2%

::Create file.csv at desired location
echo %curTimestamp%, %ping% >> %filename%

::Wait for x second before next ping
PING localhost -n %speed% >NUL

goto :ping

【讨论】:

  • 需要注意:字符串time=和%currTimeStamp%计算必须适应本地设置(语言和本地日期格式)
【解决方案2】:
@echo off

::Set the address you wish to ping
set/p host=host Address: 

set logfile=Log_%host%.log

echo Target Host = %host% >%logfile%
::for /f "tokens=*" %%A in ('ping %host% -n 1 ') do (echo %%A>>%logfile% && GOTO Ping)

:Ping
for /f "tokens=* skip=2" %%A in ('ping %host% -n 1 -l 32') do (
    echo %date% %time:~0,2%:%time:~3,2%:%time:~6,2% %%A>>%logfile%
    echo %date% %time:~0,2%:%time:~3,2%:%time:~6,2% %%A
    timeout 1 >NUL 
    GOTO Ping)

【讨论】:

  • 这就像一个魅力,并在日志文件中正确记录时间和日期以及只是一个不同的变体,所以认为它会对某些人有所帮助
猜你喜欢
  • 1970-01-01
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
  • 2014-11-21
  • 2016-08-12
  • 1970-01-01
  • 1970-01-01
  • 2013-10-13
相关资源
最近更新 更多