Ping в файл со временем windows

On the Windows command prompt cmd, I use ping -t to 10.21.11.81 Reply from 10.21.11.81: bytes=32 time=3889ms TTL=238 Reply from 10.21.11.81: bytes=32 time=3738ms TTL=238 Reply from 10.21.11.81: by...
@echo off
    ping -t localhost|find /v ""|cmd /q /v:on /c "for /l %%a in (0) do (set "data="&set /p "data="&if defined data echo(!time! !data!)" 

note: code to be used inside a batch file. To use from command line replace %%a with %a

Start the ping, force a correct line buffered output (find /v), and start a cmd process with delayed expansion enabled that will do an infinite loop reading the piped data that will be echoed to console prefixed with the current time.

2015-01-08 edited:
In faster/newer machines/os versions there is a synchronization problem in previous code, making the set /p read a line while the ping command is still writting it and the result are line cuts.

@echo off
    ping -t localhost|cmd /q /v /c "(pause&pause)>nul & for /l %%a in () do (set /p "data=" && echo(!time! !data!)&ping -n 2 localhost>nul"

Two aditional pause commands are included at the start of the subshell (only one can be used, but as pause consumes a input character, a CRLF pair is broken and a line with a LF is readed) to wait for input data, and a ping -n 2 localhost is included to wait a second for each read in the inner loop. The result is a more stable behaviour and less CPU usage.

NOTE: The inner ping can be replaced with a pause, but then the first character of each readed line is consumed by the pause and not retrieved by the set /p

Чтобы провести мониторинг стабильности сетевой доступности вашего локального ресурса,  удобно запустить ping в его сторону. И одновременно до адреса в интернете.
Таким образом мы поймем столкнулись ли мы с глобальной сетевой проблемой, или же только с сетевой недоступность вашего ресурса.
Параллельный ping удобно сопоставлять имея временные метки в истории.
По умолчанию утилита ping не возвращает метку времени отправки пакета. Поэтому давайте посмотрим как можно дополнить результат выводом времени.

Powershell

ping.exe -t 8.8.8.8 | ForEach { "{0} - {1}" -f (Get-Date),$_ }

Перенаправление в файл

ping.exe -t 8.8.8.8 | ForEach { "{0} - {1}" -f (Get-Date),$_ | Add-Content C:tempping.txt }

CMD

ping -t 8.8.8.8 | cmd /q /v /c "(pause&pause)>nul & for /l %a in () do (set /p "data=" && echo(!date! !time! !data!)&ping -n 2 8.8.8.8>nul"

Перенаправление в файл

ping -t 8.8.8.8 | cmd /q /v /c "(pause&pause)>nul & for /l %a in () do (set /p "data=" && echo(!date! !time! !data!)&ping -n 2 8.8.8.8>nul" > C:tempping.txt

Лог утилиты Ping

Лог утилиты Ping

Записки администратора

andan

Необходимо получить строчку типа:
Обмен пакетами с 192.168.213.1 по с 32 байтами данных:
[09:54:01] Ответ от 192.168.213.1: число байт=32 время<1мс TTL=64
[09:54:02] Ответ от 192.168.213.1: число байт=32 время<1мс TTL=64
...

плюс, желательно записать ее в лог. Решения нужно 2, для Windows и Linux.

То что ниже не предлагать, это издевательство:
time /t >> 1.txt & ping -n 1 xxx.yyy.zzz.www >> 1.txt

UPD: Появилось решение для Windows и для Linux.


  • Вопрос задан

    более трёх лет назад

  • 36135 просмотров

Версия для Windows:

for /l %i in (0,0,1) do @cmd /c "echo.|set/p=%TIME:~0,8^%" & ping -n 1 google.com | find "Reply" & ping -n 2 localhost > nul

Пригласить эксперта

#!/bin/bash
while true
    do
        TIME=`date +%T`
        PING=`ping $1 -c 2 | grep icmp | grep seq=2`
            echo "[$TIME] $PING" >>/tmp/pingtime.log
            echo "[$TIME] $PING" 
	sleep 5
    done

image

ping -t 8.8.8.8|cmd /q /v /c «(pause&pause)>nul & for /l %a in () do (set /p «data=» && echo(!date! !time! !data!)&ping -n 2 8.8.8.8>nul»


  • Показать ещё
    Загружается…

04 февр. 2023, в 20:45

1000 руб./за проект

04 февр. 2023, в 20:44

20000 руб./за проект

04 февр. 2023, в 20:04

35000 руб./за проект

Минуточку внимания

m9s1kk

1 / 1 / 0

Регистрация: 05.07.2011

Сообщений: 35

1

18.10.2014, 00:54. Показов 25839. Ответов 7

Метки нет (Все метки)


Почитал другие темы, но так и не допер как это сделать. Собственно нужно реализовать вывод времени рядом с каждой строчкой ответа в таком случае.

Bash
1
ping ya.ru -t > c:ping.txt

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



ComSpec

3455 / 1993 / 635

Регистрация: 26.02.2014

Сообщений: 1,457

18.10.2014, 09:11

2

Bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@echo off
 
 
:start
 
 
 for /f "skip=2 delims=" %%i in ('ping ya.ru -n 1') do call :sub "%%i"
 exit /b
 
 :sub
  chcp 1251>nul
  echo %time%. %~1>>"ping.txt"
  chcp 866>nul
  goto start



0



1 / 1 / 0

Регистрация: 05.07.2011

Сообщений: 35

18.10.2014, 11:58

 [ТС]

3

ComSpec, это работает, но скрипт сам выключается через ~30 секунд, а мне нужно чтобы он работал в течении некоторого времени, пока я сам не выключу. И слишком уж часто посылает команду. Так и хост может забанить за ддос



0



3455 / 1993 / 635

Регистрация: 26.02.2014

Сообщений: 1,457

18.10.2014, 12:20

4

m9s1kk, в контексте Вашей постановки вопроса по-другому сделать практически нельзя. Теоретически возможно создание дополнительного файла, куда будет записываться время, и совмещение обоих выходных файлов по окончании пингования.



0



Charles Kludge

Клюг

7673 / 3188 / 382

Регистрация: 03.05.2011

Сообщений: 8,380

18.10.2014, 15:15

5

Лучший ответ Сообщение было отмечено m9s1kk как решение

Решение

m9s1kk, слепил вот такое:

C
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <winbase.h>
void main(void)
  {
    SYSTEMTIME st;
 
GetLocalTime(&st);
printf("%02d.%02d.%4d %02d:%02d:%02d,%03d ",st.wDay, st.wMonth, st.wYear,
st.wHour,st.wMinute, st.wSecond, st.wMilliseconds);
};

и батник:

Bash
1
2
3
4
5
@ echo .>test.txt
:again
dttm>>test.txt
ping ya.ru -w 1000 >>test.txt
goto :again

Вложения

Тип файла: zip dttm.zip (16.4 Кб, 75 просмотров)



2



1 / 1 / 0

Регистрация: 05.07.2011

Сообщений: 35

18.10.2014, 18:10

 [ТС]

6

Charles Kludge, спасибо большое, то что надо. Только вот батник надо запускать от имени администратора. Решил что самое простое решение проблемы — поместить .exe в system32, чтобы он не искал долго путь



0



ybrukax

0 / 0 / 0

Регистрация: 31.10.2017

Сообщений: 7

31.10.2017, 09:38

7

Как-то вы все усложнили товарищи, есть более элегантное решение.
Запись результата в лог и вывод в строке cmd.

Windows Batch file
1
2
3
4
5
6
7
8
9
10
11
12
@echo off
set IP=192.168.1.1
@:begin
@for /f "tokens=1*" %%i in ('ping -n 1 %IP% ^| findstr /i "TTL Превышен"') do set n="%%i %%j"
 
@if defined n (goto log)
set n="Error"
@:log
@echo %n%
@echo %date% %time% %n% >> ping_log.txt
ping -n 2 127.0.0.1 > nul
@goto begin



0



0 / 0 / 0

Регистрация: 07.06.2017

Сообщений: 1

22.10.2019, 22:30

8

работает, весьма симпатично и очень пригодилось -)))



0



Use redirection, for example:

ping 192.168.1.1 -t > filename.txt

This will redirect all (standard) output from the program into filename.txt, which will be created if it doesn’t exist and overwritten if it does.

You can use >> instead of > to redirect the output to a file and append the results to the end of the file, instead of overwriting (with thanks to @Jane T for the reminder).

Note that you will not receive the normal on-screen output if you do this.

Update in response to comment

To delay between pings and record the time of each, you can do some scripting.

Here is a quick Windows batch file I’ve thrown together. It prints the time, pings Google, then waits for 3 seconds before repeating itself. I’m not a batch file expert so if anyone spots any problems please flag them up! And this probably isn’t the «best» way to achieve what you are after — that might make for a separate question really.

@ECHO OFF

:LOOPSTART

time /T
ping www.google.com -n 4
sleep -m 3000

GOTO LOOPSTART

Save this in a .bat file somewhere, edit the ping target and delay time as you need it, then run the .bat using redirection to pump the output of the whole thing to a file. You may need to replace the sleep -m 3000 command with timeout /T 3 depending on your Windows version.

Note that this batch file never ends, but can be terminated by Ctrl + C and then Y if run from cmd. (You must press Y because it asks if you want to stop the batch file — even though you cannot see the question because you’ve redirected the output!)

Use redirection, for example:

ping 192.168.1.1 -t > filename.txt

This will redirect all (standard) output from the program into filename.txt, which will be created if it doesn’t exist and overwritten if it does.

You can use >> instead of > to redirect the output to a file and append the results to the end of the file, instead of overwriting (with thanks to @Jane T for the reminder).

Note that you will not receive the normal on-screen output if you do this.

Update in response to comment

To delay between pings and record the time of each, you can do some scripting.

Here is a quick Windows batch file I’ve thrown together. It prints the time, pings Google, then waits for 3 seconds before repeating itself. I’m not a batch file expert so if anyone spots any problems please flag them up! And this probably isn’t the «best» way to achieve what you are after — that might make for a separate question really.

@ECHO OFF

:LOOPSTART

time /T
ping www.google.com -n 4
sleep -m 3000

GOTO LOOPSTART

Save this in a .bat file somewhere, edit the ping target and delay time as you need it, then run the .bat using redirection to pump the output of the whole thing to a file. You may need to replace the sleep -m 3000 command with timeout /T 3 depending on your Windows version.

Note that this batch file never ends, but can be terminated by Ctrl + C and then Y if run from cmd. (You must press Y because it asks if you want to stop the batch file — even though you cannot see the question because you’ve redirected the output!)

Иногда для разборок с провайдерами нужно предоставить лог, где будет зафиксировано время пропадания работоспособности сетевого канала. Как известно, работоспособность канала проверяется командой ping — пингуется один хост (или несколько), расположенный по другую сторону канала. Но, к сожалению, простой запуск ping не регистрирует время запуска такого теста. Далее описана простая процедура настройки пинга с возможностью записи в лог времени тестов.

[Пример 1]
Идея мониторинга простая — в командном файле по циклу запускается ping, и время запуска регистируется с помощью утилиты now.exe, входящей в Resource Kit. Получается лог примерно такого вида:

********************************************************************************
********************************************************************************
     Pinging only one PBX IP from Moskow
———————————————————————————
«PBX main address»
Tue Apr 29 17:08:42 2008
Pinging a.b.16.3 with 32 bytes of data:
Reply from a.b.16.3: bytes=32 time=9ms TTL=59
Reply from a.b.16.3: bytes=32 time=10ms TTL=59
Reply from a.b.16.3: bytes=32 time=10ms TTL=59
Reply from a.b.16.3: bytes=32 time=9ms TTL=59

Ping statistics for a.b.16.3:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

Approximate round trip times in milli-seconds:
    Minimum = 9ms, Maximum = 10ms, Average = 9ms

Вся система состоит из 3 файлов — pinglogger.bat, iplist.txt и pingone.bat. Файл iplist.txt содержит список пингуемых IP-адресов — в каждой строке один IP и комментарий к нему (здесь в списке только один IP, но их может быть несколько):
[Содержимое файла iplist.txt]
a.b.16.3     PBX main address

Файл pingone.bat пингует один IP из списка (вызывается изнутри файла pinglogger.bat):
[Содержимое файла pingone.bat]
@rem usage: pingone.bat IP_address «description» logfile
@echo ——————————————————————————— >> %3
@echo %2 >> %3
@now >> %3
@ping %1 >> %3

Файл pinglogger.bat запускает на бесконечный цикл процесс пингования. Его можно стартовать как вручную, так и с помощью планировщика — я обычно настраиваю задание на момент загрузки компьютера (чтобы обеспечить автоматическое возобновление работы теста в случае перезагрузки):
[Содержимое файла pinglogger.bat]
:cycle
@set log=pinglog.txt
@echo ******************************************************************************** >> %log%
@echo ******************************************************************************** >> %log%
@echo      Pinging only one PBX IP from Moskow >> %log%
@for /F «tokens=1,*» %%l in (iplist.txt) do call pingone.bat %%l «%%m» %log%
goto cycle

Немного пояснений. Вывод комментария перед циклом for предназначен для документирования начала цикла пинга всего списка IP. Цикл for разбирает список IP iplist.txt, и выделяет из каждой строки IP-адрес и комментарий. IP присваивается переменной %%l, а комментарий — переменной %%m, и с этими параметрами вызывается pingone.bat. Параметр %%m заключен в кавычки не случайно — этим разрешается использование в комментариях IP-адресов файла iplist.txt пробелов (в нашем примере комментарий — «PBX main address»). Имя файла лога pinglog.txt задается строчкой @set log=pinglog.txt. Метод обработки такого лога с помощью grep см. здесь.


В результате получается примерно такой лог:
..
********************************************************************************
********************************************************************************
     Pinging only one PBX IP from Tver
———————————————————————————
«Tver, PBX»

Tue Apr 29 17:04:32 2008
Pinging a.b.16.3 with 32 bytes of data:

Reply from a.b.16.3: bytes=32 time<1ms TTL=62
Reply from a.b.16.3: bytes=32 time<1ms TTL=62
Reply from a.b.16.3: bytes=32 time<1ms TTL=62
Reply from a.b.16.3: bytes=32 time<1ms TTL=62

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

********************************************************************************
********************************************************************************
     Pinging only one PBX IP from Tver
———————————————————————————
«Tver, PBX»

Tue Apr 29 17:04:35 2008
Pinging a.b.16.3 with 32 bytes of data:

Reply from a.b.16.3: bytes=32 time<1ms TTL=62
..

Читать его, конечно, довольно неудобно. Его можно свернуть к намного более удобной форме:
..
Wed Apr 30 10:02:40 2008 25% loss
Wed Apr 30 10:04:55 2008 25% loss
Wed Apr 30 10:07:14 2008 25% loss
Wed Apr 30 10:11:48 2008 50% loss
Wed Apr 30 10:15:25 2008 25% loss
Wed Apr 30 10:15:47 2008 75% loss
Wed Apr 30 10:22:45 2008 100% loss
Wed Apr 30 10:23:06 2008 100% loss
Wed Apr 30 10:23:48 2008 100% loss
Wed Apr 30 10:24:09 2008 100% loss
Wed Apr 30 10:29:41 2008 75% loss
Wed Apr 30 10:31:51 2008 25% loss
Wed Apr 30 10:35:15 2008 25% loss
Wed Apr 30 10:36:42 2008 100% loss
Wed Apr 30 10:37:03 2008 75% loss
Wed Apr 30 10:38:00 2008 75% loss
Wed Apr 30 10:38:16 2008 100% loss
Wed Apr 30 10:38:58 2008 100% loss
Wed Apr 30 10:39:19 2008 100% loss
Wed Apr 30 10:39:40 2008 100% loss
Wed Apr 30 10:40:01 2008 75% loss
Wed Apr 30 10:47:39 2008 25% loss
Wed Apr 30 10:54:58 2008 25% loss
Wed Apr 30 10:55:39 2008 25% loss
..

Это можно сделать с помощью скрипта на sh (Linux):
[..]# ./pingfilter.sh /root/tver_piter.txt all
Tue Apr 29 17:09:02 2008 25% loss
Tue Apr 29 17:26:08 2008 25% loss
..

На входе скрипта первым параметром указывается путь к сырому логу, а вторым параметром указывается фильтр. Варианты фильтра — all, 25%, 50%, 75%, 100%. Все скрипты можно скачать здесь. Назначение файлов:
windows80424pingPBX.bat
   основной файл, запуск которого включает накопление лога. Можно запустить как вручную, так и настроить задание планировщика (этот вариант предпочтительнее), настроить выполнять задание при запуске компьютера, убрать ограничение на время работы. В этом файле в цикле for указывается текстовый список IP-адресов для пингования.
windowspingone.bat
   список команд для пинга, который вызывается из основного файла 080424pingPBX.bat
windowsnow.exe
   утилита из Resource Kit, нужна для фиксации времени в логе.
windowspbxIP.txt
windowsphonesIP.txt
windowsweigtlyIP.txt
   примеры списков IP (каждому IP в строке можно добавить комментарий)
windowspingPBXlog.txt
   пример лога — результата работы 080424pingPBX.bat
Linuxpingfilter.sh
   Фильтр для сырого лога. Usage: sh ./pingfilter.sh <logfilename> <all|25%|50%|75%|100%>
Linuxpatt2.txt
   список фильтров для grep, используется в pingfilter.sh
Linuxglue-ping-strings.pl
   Скрипт на perl, который используется внутри pingfilter.sh для служебных целей обработки строк.


[Пример 2]

Этот пример попроще, состоит из скрипта timepinger.vbs, который делает одиночный ping и пишет результат в лог вместе со временем, и bat-файла ping-infinite.bat, который запускает этот скрипт с интервалом в 1 секунду.

[ping-infinite.bat]
:loop
timepinger.vbs a.b.48.254 logfile.txt
sleep 1
goto loop

[timepinger.vbs]
Dim Args
Set Args = WScript.Arguments

if (Args.Count < 2) then
    MsgBox «Usage:» + vbCrLf + «timepinger.vbs <IP> <logfile>»
else
    line = vbNullString
    ‘получаем аргументы
    IP = Args(0)
    logfile = Args(1)
    ‘получаем дату/время
    vYear   = CStr(Year   (Date))
    vMonth  = CStr(Month  (Date))
    if Len(vMonth) < 2 then
        vMonth = «0»+vMonth
    end if
    vDay    = CStr(Day    (Date))
    if Len(vDay) < 2 then
        vDay = «0»+vDay
    end if
    vHour   = CStr(Hour   (Time))
    if Len(vHour) < 2 then
        vHour = «0»+vHour
    end if
    vMinute = CStr(Minute (Time))
    if Len(vMinute) < 2 then
        vMinute = «0»+vMinute
    end if
    vSecond = CStr(Second (Time))
    if Len(vSecond) < 2 then
        vSecond = «0»+vSecond
    end if
    timestamp = «[«+vDay+».»+vMonth+».»+vYear+» «+vHour+»:»+vMinute+»:»+vSecond+»]»
    ‘подготавливаем выходной лог
    Set FSO = CreateObject(«Scripting.FileSystemObject»)
    Set FileOutStream = FSO.OpenTextFile(logfile, 8, true, 0)
    ‘запускаем ping
    Set WshShell = CreateObject(«WScript.Shell»)
    Set WshExec = WshShell.Exec(«ping » + IP + » -n 1″)
    ‘обрабатываем вывод ping
    Set ConsoleStream = WshExec.StdOut
    While Not ConsoleStream.AtEndOfStream
        line = Trim(ConsoleStream.ReadLine())
        if (0 < InStr (line, «Reply from»)) or (0 < InStr (line, «Request timed out»)) then
            poscrlf = InStr (line, CStr(Chr(13)))
            line = Mid (line, 1, poscrlf-1)
            FileOutStream.Write timestamp + » » + line & vbCrLf
        end if
    Wend
end if

Вот пример лога logfile.txt, который получается на выходе (его удобно отфильтровать утилитой grep с ключами -A и -B, см. grep: примеры использования):
[07.11.2008 14:07:21] Reply from a.b.48.254: bytes=32 time=82ms TTL=253
[07.11.2008 14:07:23] Reply from a.b.48.254: bytes=32 time=130ms TTL=253
[07.11.2008 14:07:24] Reply from a.b.48.254: bytes=32 time=143ms TTL=253
[07.11.2008 14:07:26] Reply from a.b.48.254: bytes=32 time=121ms TTL=253
[07.11.2008 14:07:27] Reply from a.b.48.254: bytes=32 time=90ms TTL=253
[07.11.2008 14:07:29] Request timed out.
[07.11.2008 14:07:34] Reply from a.b.48.254: bytes=32 time=11ms TTL=253
[07.11.2008 14:07:36] Reply from a.b.48.254: bytes=32 time=193ms TTL=253
[07.11.2008 14:07:37] Reply from a.b.48.254: bytes=32 time=214ms TTL=253
[07.11.2008 14:07:39] Reply from a.b.48.254: bytes=32 time=171ms TTL=253
[07.11.2008 14:07:40] Reply from a.b.48.254: bytes=32 time=161ms TTL=253
[07.11.2008 14:07:42] Reply from a.b.48.254: bytes=32 time=53ms TTL=253
[07.11.2008 14:07:43] Reply from a.b.48.254: bytes=32 time=132ms TTL=253
[07.11.2008 14:07:45] Reply from a.b.48.254: bytes=32 time=167ms TTL=253
[07.11.2008 14:07:46] Reply from a.b.48.254: bytes=32 time=94ms TTL=253
[07.11.2008 14:07:48] Request timed out.
[07.11.2008 14:07:53] Reply from a.b.48.254: bytes=32 time=103ms TTL=253
[07.11.2008 14:07:55] Reply from a.b.48.254: bytes=32 time=209ms TTL=253
[07.11.2008 14:07:56] Reply from a.b.48.254: bytes=32 time=194ms TTL=253
[07.11.2008 14:07:58] Reply from a.b.48.254: bytes=32 time=138ms TTL=253

Понравилась статья? Поделить с друзьями:
  • Pinball скачать на компьютер windows 10
  • Pinnacle плата видеозахвата pci драйвер windows 10
  • Pinnacle tvcenter pro для windows xp скачать
  • Pinball windows xp скачать для андроид
  • Pinnacle tvcenter pro для windows 7 x64