Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: ping an address, log errors to text file with timestamp  (Read 187822 times)

0 Members and 1 Guest are viewing this topic.

boff

    Topic Starter


    Greenhorn

    • Experience: Beginner
    • OS: Unknown
    ping an address, log errors to text file with timestamp
    « on: June 10, 2011, 11:00:11 PM »
    Hi,
    I am aware that this requirement has been answered in a number of different ways, but none of them seemed that elegant to me (by elegant read short & simple).
    I would like to leave a ping running (ping -t) and have any response that is a not a reply be written to a text file along with the time and date.

    It's the time and date thing that's got me stumped.

    First bit working fine for me:

    ping -t 195.40.1.36 | find /v "Reply from 195.40.1.36" >> pinglog.txt

    Could anyone please let me know how to add the time and date to what gets written out.
    Many thanks.

    boff

      Topic Starter


      Greenhorn

      • Experience: Beginner
      • OS: Unknown
      Re: ping an address, log errors to text file with timestamp
      « Reply #1 on: June 11, 2011, 01:41:46 AM »
      Not too sure where you're going with that one. Doesn't seem to work for me.
      I get the failed pings written out to a log file but they aren't timestamped.

      I could use the following batch file. Works fine, but it doesn't record the reason for failure, just that it did fail and the time it happened (and there's probably a cleverer way to pause for 1 second.....)

      The reason for failure would be really handy.

      @echo off
      :loop
      ping -n 1 %1 >nul || echo %date% %time% no reply from %1 >> pinglog.txt
      choice /N /T 1 /D Y >nul
      goto loop



      boff

        Topic Starter


        Greenhorn

        • Experience: Beginner
        • OS: Unknown
        Re: ping an address, log errors to text file with timestamp
        « Reply #2 on: June 11, 2011, 02:35:42 AM »
        I don't want him to bounce me into posting an untested and incompletely considered reply. Please bear with us a little longer!

        No worries and much appreciated.

        Salmon Trout

        • Guest
        Re: ping an address, log errors to text file with timestamp
        « Reply #3 on: June 11, 2011, 06:15:53 AM »
        The script below addresses the simplest case I can think of, namely a host which exists and which either is or is not servicing ping requests. If the ping command is "successful" then it looks like this...

        Code: [Select]
        C:\>ping -n 1 192.168.56.129

        Pinging 192.168.56.129 with 32 bytes of data:
        Reply from 192.168.56.129: bytes=32 time<1ms TTL=128

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

        If not, it looks like this

        Code: [Select]
        C:\>ping -n 1 192.168.56.129

        Pinging 192.168.56.129 with 32 bytes of data:
        Request timed out.

        Ping statistics for 192.168.56.129:
            Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),

        I only send 1 request for the sake of avoiding network congestion

        The IP I am using is a local XP machine whose firewall I turn on and off

        As you will see the meat is in the 2nd non-blank line, and we can examine this and decide whether to write it to a log file, preceded by the date and time. To make a delay I use the free sleep utility which is part of the Windows Server 2003 Resource Kit Tools which you can download here:

        http://www.microsoft.com/downloads/en/confirmation.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd

        There are plenty of others around but not all have the -m (milliseconds) feature.

        Code: [Select]
        @echo off
        setlocal enabledelayedexpansion
        set hostIP=192.168.56.129
        :loop
        set pingline=1
        for /f "delims=" %%A in ('ping -n 1 -w 250 -l 255 %hostIP%') do (
        if !pingline! equ 2 (
        set logline=!date! !time! "%%A"
        echo !logline! | find "TTL=">nul || echo !logline! >> pinglog.txt
        )
        set /a pingline+=1
        )
        sleep -m 5000
        goto loop


        The IP you used as an example resolves to lr-rns.timik.uk.easynet.net on my machine; I wonder if you are wanting to log times and/or periods of bad Internet connection or whether it was just an example?
        « Last Edit: June 11, 2011, 06:44:03 AM by Salmon Trout »

        boff

          Topic Starter


          Greenhorn

          • Experience: Beginner
          • OS: Unknown
          Re: ping an address, log errors to text file with timestamp
          « Reply #4 on: June 11, 2011, 06:36:01 AM »
          Thank you so much. Works perfectly.
          I'll need to substitute my delay
          choice /N /T 1 /D Y >nul
          for your rather neater sleep utility as I don't have the option of installing anything.

          Are you doing a FIND on "TTL" because it is only a healthy reply that would ever have those characters in it?

          The IP I used in the example is just an ISP's nameserver that hasn't changed in 15 years and for some reason I've always defaulted to it.

          I'll be using the script to troubleshoot an intermittent network dropout on some servers at work. I plan on pinging a known good IP (our main data centre router) from multiple servers. By correlating the logs I should be able to determine if the dropouts are due to OS, hypervisor, switch or data centre (at least that's my theory!).

          Thanks again. Love your nic by the way, started reading 'The Salmon of Doubt' by Douglas Adams just yesterday.

          Salmon Trout

          • Guest
          Re: ping an address, log errors to text file with timestamp
          « Reply #5 on: June 11, 2011, 07:25:47 AM »
          Are you doing a FIND on "TTL" because it is only a healthy reply that would ever have those characters in it?

          Yup. Note the || operator (execute 2nd command if 1st command returns nonzero errorlevel - the opposite of &&)


          Salmon Trout

          • Guest
          Re: ping an address, log errors to text file with timestamp
          « Reply #6 on: June 11, 2011, 07:39:48 AM »
          Also note that the message "Request timed out" is quoted because I am echoing %%A, the 2nd nonblank line of the ping output, via a pipe to find, and a healthy response on my system shows the response time field as "time<1mS" and the < symbol in an unquoted literal string or expanded variable breaks script processing because it has a special meaning (redirection).

          Salmon Trout

          • Guest
          Re: ping an address, log errors to text file with timestamp
          « Reply #7 on: June 11, 2011, 07:48:52 AM »
          If you don't want the quotes to appear in the log see below

          Code: [Select]
          @echo off
          setlocal enabledelayedexpansion
          set hostIP=192.168.56.129
          :loop
          set pingline=1
          for /f "delims=" %%A in ('ping -n 1 -w 250 -l 255 %hostIP%') do (
          if !pingline! equ 2 (
          set logline=!date! !time! "%%A"
          echo !logline! | find "TTL=">nul || (
          set logline=!logline:"=!
          echo !logline! >> pinglog.txt
          )
          )
          set /a pingline+=1
          )
          sleep -m 5000
          goto loop
             

          Before...

          Code: [Select]
          11/06/2011 14:44:42.28 "Request timed out." 
          11/06/2011 14:44:47.78 "Request timed out." 
          11/06/2011 14:44:53.28 "Request timed out." 
          11/06/2011 14:44:58.78 "Request timed out." 
          11/06/2011 14:45:04.28 "Request timed out." 
          11/06/2011 14:45:09.78 "Request timed out." 
          11/06/2011 14:45:15.28 "Request timed out." 
          11/06/2011 14:45:20.78 "Request timed out." 

          After...

          Code: [Select]
          11/06/2011 14:47:11.28 Request timed out. 
          11/06/2011 14:47:16.78 Request timed out. 
          11/06/2011 14:47:22.28 Request timed out. 
          11/06/2011 14:47:27.78 Request timed out. 
          11/06/2011 14:47:33.28 Request timed out. 
          11/06/2011 14:47:38.78 Request timed out. 
          11/06/2011 14:47:44.28 Request timed out. 
          11/06/2011 14:47:49.78 Request timed out. 
          11/06/2011 14:47:55.28 Request timed out. 
          11/06/2011 14:48:00.78 Request timed out. 
          11/06/2011 14:48:06.28 Request timed out. 

          Salmon Trout

          • Guest
          Re: ping an address, log errors to text file with timestamp
          « Reply #8 on: June 11, 2011, 03:08:10 PM »
          Alternative method using VBScript - save with .vbs extension and call with cscript.exe supplying IP and log file name. In some ways more "elegant", maybe?

          e.g. cscript mypingscript.vbs 192.168.56.129 logfile.txt

          Code: [Select]
          hostIp      = wscript.arguments(0)
          logfilename = wscript.arguments(1)
          Set fso     = CreateObject("Scripting.FileSystemObject")
          Set Shell   = CreateObject("Wscript.Shell")
          Set logfile = fso.OpenTextFile(logfilename, 8, True)
          shellstring = "%comspec% /c ping -t " & hostIP
          Set oExec   = Shell.Exec(shellstring)
          wscript.echo "Ping Error log With Timestamp - Ctrl + C to halt"
          Do While oExec.StdOut.AtEndOfStream <> True
          pingline = Date & " " & Time & " " & oExec.StdOut.ReadLine
          If Not InStr(pingline, "TTL=") Then
          logfile.WriteLine(pingline)
          End If
          Loop


          boff

            Topic Starter


            Greenhorn

            • Experience: Beginner
            • OS: Unknown
            Re: ping an address, log errors to text file with timestamp
            « Reply #9 on: June 11, 2011, 04:10:35 PM »
            Alternative method using VBScript

            The nice thing about that one is that when you exit the script the ping stats get written to the log file.  Unfortunately for me every line is being written to the log file (the "TTL=" isn't working). The original dos script you wrote is perfect though. Thanks again.

            Salmon Trout

            • Guest
            Re: ping an address, log errors to text file with timestamp
            « Reply #10 on: June 11, 2011, 06:03:28 PM »
            Unfortunately for me every line is being written to the log file (the "TTL=" isn't working).

            Sorry about that...

            hostIp      = wscript.arguments(0)
            logfilename = wscript.arguments(1)
            Set fso     = CreateObject("Scripting.FileSystemObject")
            Set Shell   = CreateObject("Wscript.Shell")
            ' OpenTextFile Method requires a Const value
            ' (Over)Write = 2  Append = 8   
            Set logfile = fso.OpenTextFile(logfilename, 8, True)
            shellstring = "%comspec% /c ping -t " & hostIP
            Set oExec   = Shell.Exec(shellstring)
            wscript.echo "Ping Error log With Timestamp - Ctrl + C to halt"
            Do While oExec.StdOut.AtEndOfStream <> True
                  pingline = Date & " " & Time & " " & oExec.StdOut.ReadLine
                  If InStr(pingline, "TTL=") = 0 Then
                     logfile.WriteLine(pingline)
                  End If
            Loop


            boff

              Topic Starter


              Greenhorn

              • Experience: Beginner
              • OS: Unknown
              Re: ping an address, log errors to text file with timestamp
              « Reply #11 on: June 11, 2011, 10:11:39 PM »
              Fantastic. Will implement tonight and let you know how it goes in a couple of days.
              The fact that with the vbscript you get the ping stats for the whole session written to the tail of the log file is very cool.

              mmediaman



                Newbie

                • Experience: Beginner
                • OS: Unknown
                Re: ping an address, log errors to text file with timestamp
                « Reply #12 on: June 05, 2012, 09:04:54 AM »
                Wanted to take the time to register on this forum and congratulate Salmon Trout for providing a 1st class solution.  I have looked far and wide for something elegant, simple, robust that works and was only able to find it in Salmon's solution. 

                I added TRACERT into the single logical operator line to get additional useful information for troubleshooting:

                echo !logline! | find "TTL=">nul || echo !logline! >> NetworkPingErrors.txt && echo Running TraceRT, please wait.... && tracert %hostIP% >> NetworkPingErrors.txt && echo ----------- >> NetworkPingErrors.txt
                 
                Thank you very much sir!  Hats off to you.

                Salmon Trout

                • Guest
                Re: ping an address, log errors to text file with timestamp
                « Reply #13 on: June 05, 2012, 09:43:57 AM »
                Nice to see after nearly a year that somebody found it useful.

                mmedia man, you are using the double ampersand (&&) as a command separator, I hope you remember it is actually an AND operator - that is:

                command1 && command2     command2 is only executed if command1 returns a zero errorlevel

                The opposite is the double pipe OR operator.

                command1 || command2     command2 is only executed if command1 returns a non-zero errorlevel

                The ordinary command separator is a single ampersand

                command1 & command2 command2 is always executed



                example:

                Code: [Select]
                C:\>dir /b notexist.fil && echo command2
                File Not Found

                C:\>dir /b notexist.fil & echo command2
                File Not Found
                command2

                In most cases it may not matter which one you use, but there may come a situation where a string of commands on one line will halt part way through if you use && when you don't actually intend to test the preceding errorlevel.


                denywinarto



                  Newbie

                  • Experience: Beginner
                  • OS: Unknown
                  Re: ping an address, log errors to text file with timestamp
                  « Reply #14 on: August 28, 2012, 11:07:47 PM »
                  Sorry about that...

                  hostIp      = wscript.arguments(0)
                  logfilename = wscript.arguments(1)
                  Set fso     = CreateObject("Scripting.FileSystemObject")
                  Set Shell   = CreateObject("Wscript.Shell")
                  ' OpenTextFile Method requires a Const value
                  ' (Over)Write = 2  Append = 8   
                  Set logfile = fso.OpenTextFile(logfilename, 8, True)
                  shellstring = "%comspec% /c ping -t " & hostIP
                  Set oExec   = Shell.Exec(shellstring)
                  wscript.echo "Ping Error log With Timestamp - Ctrl + C to halt"
                  Do While oExec.StdOut.AtEndOfStream <> True
                        pingline = Date & " " & Time & " " & oExec.StdOut.ReadLine
                        If InStr(pingline, "TTL=") = 0 Then
                           logfile.WriteLine(pingline)
                        End If
                  Loop


                  just registered this forum to thank you for such an excellent script.
                  however, it still does not print
                  "request timed out"
                  in my case..
                  it simply writes
                  "ping request could not find host www.google.com. Please check the name and try again."

                  for my case i need to count how many RTO's occured to measure the bandwidth quality.
                  so is there anyway to make it print the rto's as well?
                  thanks