Script to collect & clear event logs from remote PCs and deposit to a central location.

Author Message
mtw999

  • Total Posts : 29
  • Scores: 0
  • Reward points : 0
  • Joined: 8/22/2011
  • Status: offline
Script to collect & clear event logs from remote PCs and deposit to a central location. Tuesday, August 23, 2011 1:53 AM (permalink)
0
[Helpful answer received] / [List Solutions Only]
Special thanks to ebgreen for helping me clean this up a bit, if anyone knows how to do this without the "On Error Resume Next" line, by all means go for it. I am still reading up on it at the moment
 
This script is run from a "syslog" server, where all the file backups will be deposited. A .txt file will be needed that contains the IPs of all the remote machines to collect logs from.
The script will create a folder based on the current date to deposit event logs. Then, a list of IPs is read from a txt file and the script will connect to each, in turn, to perform several tasks.
If the connection is made:
    1. Create a folder c:\logs
    2. Back up four event logs, using current date and machine IP as part of the name 
    3. Clear the logs
    4. Move the logs to the syslog server
Else:
    1. Create/append an error log with data concerning any connection issues encountered
 
The script should repeat the process for every IP in the list. Once the tasks are completed, the script will Wscript.Echo one of two messages, depending on whether connection errors were encountered or not.
 
I imagine someone could make this fancy by using code to pull machines from AD if they are so inclined or could use an array if there are just a few machines to collect logs from.
*Currently, I am working on a script to pull IIS logs from remote machines as well, but it's giving me some "twist and turns."
 
 
Hope this is useful to someone!
 
NOTE: Make sure the script works before removing the ' from all four "objLogFile.ClearEventLog()" lines!
 
 
On Error Resume Next
'=== variables that assist in naming files and folders.
dtmThisDay = Day(Now)
dtmThisMonth = Month(Now)
dtmThisYear = Year(Now)
strDate = dtmThisYear & "_" & dtmThisMonth & "_" & dtmThisDay
strBackupName = strDate & "_"
'=== creates folder based on current date to deposit event logs.
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.CreateFolder("E:\logs\evtlogs\" & strDate)
'=== Opens list of computers for remote connection.
Const ForReading = 1
Set objFile = objFSO.OpenTextFile("C:\scripts\computers.txt")
'=== A Loop that will either connect to remote machines from the list, create a backup folder, back up and clear event logs
'=== and then move the backups to the syslog server OR generate an error log with data concerning the failed connection.
Do Until objFile.AtEndOfStream
    strComputer = objFile.ReadLine
   
    Set objWMIService = GetObject _
 ("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
'25
    '=== creates c:\logs on remote machine
    If Err.Number = 0 Then 
 errReturn = objWMIService.Create ("cmd.exe /c md c:\logs", Null, Null, intProcessID)
 
        Set objWMIService = GetObject("winmgmts:" _
            & "{impersonationLevel=impersonate,(Backup, Security)}!\\" & _
                strComputer & "\root\cimv2")
 Set colLogFiles = objWMIService.ExecQuery _
            ("SELECT * FROM Win32_NTEventLogFile where LogFileName='Application'")
        For Each objLogfile in colLogFiles
            objLogFile.BackupEventLog("c:\logs\" & strBackupName & strComputer & "_application.evt")
            'objLogFile.ClearEventLog()
        Next
 Set colLogFiles = objWMIService.ExecQuery _
            ("SELECT * FROM Win32_NTEventLogFile where LogFileName='Security'")
        For Each objLogfile in colLogFiles
            objLogFile.BackupEventLog("c:\logs\" & strBackupName & strComputer & "_security.evt")
            'objLogFile.ClearEventLog()
        Next
'47
 Set colLogFiles = objWMIService.ExecQuery _
            ("SELECT * FROM Win32_NTEventLogFile where LogFileName='System'")
        For Each objLogfile in colLogFiles
            objLogFile.BackupEventLog("c:\logs\" & strBackupName & strComputer & "_system.evt")
            'objLogFile.ClearEventLog()
        Next
 Set colLogFiles = objWMIService.ExecQuery _
            ("SELECT * FROM Win32_NTEventLogFile where LogFileName='Tumbleweed'")
        For Each objLogfile in colLogFiles
            objLogFile.BackupEventLog("c:\logs\" & strBackupName & strComputer & "_tumbleweed.evt")
            'objLogFile.ClearEventLog()
        Next
 '=== moves event logs to syslog server
 strRemoteFile = "\\syslog server IP\e$\logs\evtlogs\" & strDate
 objFSO.MoveFile "\\" & strComputer & "\C$\logs\*.evt", strRemoteFile
    Else
 bError = true 
 Const ForAppending = 8
'67 
 '=== Creates connection error log
 Set objLogFile = objFSO.OpenTextFile("E:\logs\evtlogs\" & strDate & "_Error Log.txt", ForAppending, True)
      objLogFile.Write "No connection to " & strComputer & ": " & Err.Description & "."
     objLogFile.Writeline 
    Err.Clear
    End If
Loop
objLogFile.Close
objFile.Close
If bError <> 0 Then
    Wscript.Echo "Logfile backup is complete. Please check the error logs."   
Else
    Wscript.Echo "Logfile backup is complete."
End If
bError = Nothing
<message edited by mtw999 on Tuesday, August 23, 2011 2:35 AM>
 
#1
    ebgreen

    • Total Posts : 8227
    • Scores: 98
    • Reward points : 0
    • Joined: 7/12/2005
    • Status: online
    Re:Script to collect & clear event logs from remote PCs and deposit to a central location. Tuesday, August 23, 2011 2:10 AM (permalink)
    0
    [This post was marked as helpful]
    The way you do it without that line is you delete that line. That is the simple answer. The slightly more complex answer is that you then look at your code for anticipated failure points. You then implement localized error handling for that anticipated failur. The pseudo code for how to do this is:
     
    On Error Resume Next
    COMMAND THAT MIGHT ERROR
    If Err.Number <> 0 Then
    HANDLE THE ERROR
    End If
    On Error Goto 0
     
     
    Also I will point out that bError is still not a good variable name. You are assigning an integer to the variable. Go back and read my original suggestion on that point. If you want to use integers name it something like nError. The best solution is to use actual booleans (True and False) and leave the name as bError.
    "... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
    Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
    http://www.visualbasicscript.com/m_47117/tm.htm
     
    #2
      mtw999

      • Total Posts : 29
      • Scores: 0
      • Reward points : 0
      • Joined: 8/22/2011
      • Status: offline
      Re:Script to collect & clear event logs from remote PCs and deposit to a central location. Tuesday, August 23, 2011 2:17 AM (permalink)
      0
      ebgreen


      The way you do it without that line is you delete that line. That is the simple answer. The slightly more complex answer is that you then look at your code for anticipated failure points. You then implement localized error handling for that anticipated failur. The pseudo code for how to do this is:
       
      On Error Resume Next
      COMMAND THAT MIGHT ERROR
      If Err.Number <> 0 Then
      HANDLE THE ERROR
      End If
      On Error Goto 0
       
       
      Also I will point out that bError is still not a good variable name. You are assigning an integer to the variable. Go back and read my original suggestion on that point. If you want to use integers name it something like nError. The best solution is to use actual booleans (True and False) and leave the name as bError.

      Actually, your suggestion was "half" implemented, lol... I changed the name to bError and forgot to implement the rest after a series of "interruptions" heheh... Thanks for the correction!

       
      #3
        mtw999

        • Total Posts : 29
        • Scores: 0
        • Reward points : 0
        • Joined: 8/22/2011
        • Status: offline
        Re:Script to collect & clear event logs from remote PCs and deposit to a central location. Wednesday, August 24, 2011 7:11 AM (permalink)
        0
        Here is an updated/modified version that provides more error checking/logging:
         
        '=== variables.
        Const ForAppending = 8
        dtmThisDay = Day(Now)
        dtmThisMonth = Month(Now)
        dtmThisYear = Year(Now)
        strDate = dtmThisYear & "_" & dtmThisMonth & "_" & dtmThisDay
        strBackupName = strDate & "_"
        '=== creates folder based on current date to deposit event logs.
        Set objFSO = CreateObject("Scripting.FileSystemObject")
        If objFSO.FolderExists("E:\logs\evtlogs\" & strDate) Then
            Set objFolder = objFSO.GetFolder("E:\logs\evtlogs\" & strDate)
        Else
            objFSO.CreateFolder("E:\logs\evtlogs\" & strDate)
        End If
        '=== Opens list of computers for remote connection.
        Const ForReading = 1
        Set objFile = objFSO.OpenTextFile("C:\scripts\computers.txt")
        '=== A Loop that will either connect to remote machines from the list, create a backup folder, back up and clear event logs
        '=== and then move the backups to the syslog server OR generate an error log with data concerning the failed connection.
        Do Until objFile.AtEndOfStream
        '25
            strComputer = objFile.ReadLine
            On Error Resume Next
            Set objWMIService = GetObject ("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
            '=== creates c:\logs on remote machine
            If Err.Number = 0 Then 
         errReturn = objWMIService.Create ("cmd.exe /c md c:\logs", Null, Null, intProcessID)
         
                Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate,(Backup, Security)}!\\" & strComputer & "\root\cimv2")
         Set colLogFiles = objWMIService.ExecQuery ("SELECT * FROM Win32_NTEventLogFile where LogFileName='Application'")
                For Each objLogfile in colLogFiles
                    objLogFile.BackupEventLog("c:\logs\" & strBackupName & strComputer & "_application.evt")
                    'objLogFile.ClearEventLog()
                Next
         Set colLogFiles = objWMIService.ExecQuery ("SELECT * FROM Win32_NTEventLogFile where LogFileName='Security'")
                For Each objLogfile in colLogFiles
                    objLogFile.BackupEventLog("c:\logs\" & strBackupName & strComputer & "_security.evt")
                    'objLogFile.ClearEventLog()
                Next
         Set colLogFiles = objWMIService.ExecQuery ("SELECT * FROM Win32_NTEventLogFile where LogFileName='System'")
                For Each objLogfile in colLogFiles
                    objLogFile.BackupEventLog("c:\logs\" & strBackupName & strComputer & "_system.evt")
                    'objLogFile.ClearEventLog()
                Next
        '52
         Set colLogFiles = objWMIService.ExecQuery ("SELECT * FROM Win32_NTEventLogFile where LogFileName='Tumbleweed'")
                For Each objLogfile in colLogFiles
                    objLogFile.BackupEventLog("c:\logs\" & strBackupName & strComputer & "_tumbleweed.evt")
                    'objLogFile.ClearEventLog()
                Next
         '=== moves event logs to syslog server
         On Error Resume Next
         strRemoteFile = "\\syslog svr IP\e$\logs\evtlogs\" & strDate
         objFSO.MoveFile "\\" & strComputer & "\C$\logs\*.evt", strRemoteFile
         If Err.Number <> 0 Then
             bError = true
              
             Set objLogFile = objFSO.OpenTextFile("E:\logs\evtlogs\" & strDate & "_Error Log.txt", ForAppending, True)
          objLogFile.Write "Error moving files from " & strComputer & ": " & Err.Description & "."
          objLogFile.Writeline
          objLogFile.Close
         End If 
         On Error Goto 0
            Else
         bError = true 
         
         '=== Creates connection error log
         Set objLogFile = objFSO.OpenTextFile("E:\logs\evtlogs\" & strDate & "_Error Log.txt", ForAppending, True)
              objLogFile.Write "No connection to " & strComputer & ": " & Err.Description & "."
             objLogFile.Writeline
             objLogFile.Close 
            End If
            On Error Goto 0
        '81
        Loop
        objFile.Close
        If bError <> 0 Then
            Wscript.Echo "Logfile backup is complete. Please check the error logs."   
        Else
            Wscript.Echo "Logfile backup is complete."
        End If
        <message edited by mtw999 on Wednesday, August 24, 2011 7:30 AM>
         
        #4
          ebgreen

          • Total Posts : 8227
          • Scores: 98
          • Reward points : 0
          • Joined: 7/12/2005
          • Status: online
          Re:Script to collect & clear event logs from remote PCs and deposit to a central location. Wednesday, August 24, 2011 7:15 AM (permalink)
          0
          This is better, but every time that you use On Error Resume next, there should be a matching On Error Goto 0 immediately after the command that you think might throw an error.
          "... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
          Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
          http://www.visualbasicscript.com/m_47117/tm.htm
           
          #5
            mtw999

            • Total Posts : 29
            • Scores: 0
            • Reward points : 0
            • Joined: 8/22/2011
            • Status: offline
            Re:Script to collect & clear event logs from remote PCs and deposit to a central location. Wednesday, August 24, 2011 7:29 AM (permalink)
            0
            ebgreen


            This is better, but every time that you use On Error Resume next, there should be a matching On Error Goto 0 immediately after the command that you think might throw an error.

             
            Missed it here, I assume:
            On Error Resume Next
             strRemoteFile = "\\syslog svr IP\e$\logs\evtlogs\" & strDate
             objFSO.MoveFile "\\" & strComputer & "\C$\logs\*.evt", strRemoteFile
             If Err.Number <> 0 Then
                 bError = true
                  
                 Set objLogFile = objFSO.OpenTextFile("E:\logs\evtlogs\" & strDate & "_Error Log.txt", ForAppending, True)
              objLogFile.Write "Error moving files from " & strComputer & ": " & Err.Description & "."
              objLogFile.Writeline
              objLogFile.Close
             End If 
             On Error Goto 0

            Thanks again!
            Corrected


             
            #6
              ebgreen

              • Total Posts : 8227
              • Scores: 98
              • Reward points : 0
              • Joined: 7/12/2005
              • Status: online
              Re:Script to collect & clear event logs from remote PCs and deposit to a central location. Wednesday, August 24, 2011 7:39 AM (permalink)
              0
              Actually it should be:

              strRemoteFile = "\\syslog svr IP\e$\logs\evtlogs\" & strDate
              On Error Resume Next
              objFSO.MoveFile "\\" & strComputer & "\C$\logs\*.evt", strRemoteFile
              On Error Goto 0
              If Err.Number <> 0 Then 
              bError = true 

              Set objLogFile = objFSO.OpenTextFile("E:\logs\evtlogs\" & strDate & "_Error Log.txt", ForAppending, True) 
              objLogFile.Write "Error moving files from " & strComputer & ": " & Err.Description & "." 
              objLogFile.Writeline 
              objLogFile.Close 
              End If
              "... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
              Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
              http://www.visualbasicscript.com/m_47117/tm.htm
               
              #7
                ebgreen

                • Total Posts : 8227
                • Scores: 98
                • Reward points : 0
                • Joined: 7/12/2005
                • Status: online
                Re:Script to collect & clear event logs from remote PCs and deposit to a central location. Wednesday, August 24, 2011 7:40 AM (permalink)
                0
                Remember the purpose is to bracket just the command that you want to handle errors for yourself and nothing more.
                "... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
                Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
                http://www.visualbasicscript.com/m_47117/tm.htm
                 
                #8
                  mtw999

                  • Total Posts : 29
                  • Scores: 0
                  • Reward points : 0
                  • Joined: 8/22/2011
                  • Status: offline
                  Re:Script to collect & clear event logs from remote PCs and deposit to a central location. Wednesday, August 24, 2011 8:11 AM (permalink)
                  0
                  ebgreen


                  Remember the purpose is to bracket just the command that you want to handle errors for yourself and nothing more.

                  Understood.
                  I know the event log backups will not overwrite existing files, so I don't think those sections need error handling. Creation of c:\logs simply moves on if the folder already exists, so the only places I think may need error handling is the "connect to remote machine or append error log" section and the "move files" section. Those were the only two sections throwing errors during testing when I removed the big, nasty "On Error Resume Next" from the top
                   
                  #9
                    mtw999

                    • Total Posts : 29
                    • Scores: 0
                    • Reward points : 0
                    • Joined: 8/22/2011
                    • Status: offline
                    Re:Script to collect & clear event logs from remote PCs and deposit to a central location. Thursday, August 25, 2011 12:15 AM (permalink)
                    0
                    ebgreen


                    Actually it should be:

                    strRemoteFile = "\\syslog svr IP\e$\logs\evtlogs\" & strDate
                    On Error Resume Next
                    objFSO.MoveFile "\\" & strComputer & "\C$\logs\*.evt", strRemoteFile
                    On Error Goto 0
                    If Err.Number <> 0 Then 
                    bError = true 

                    Set objLogFile = objFSO.OpenTextFile("E:\logs\evtlogs\" & strDate & "_Error Log.txt", ForAppending, True) 
                    objLogFile.Write "Error moving files from " & strComputer & ": " & Err.Description & "." 
                    objLogFile.Writeline 
                    objLogFile.Close 
                    End If

                    ahhh, ok!
                    I was confused a bit, your previous post suggested "On Error Goto 0" in a different spot. I'll make the changes and test it out, thanks!

                     
                    #10
                      mtw999

                      • Total Posts : 29
                      • Scores: 0
                      • Reward points : 0
                      • Joined: 8/22/2011
                      • Status: offline
                      Re:Script to collect & clear event logs from remote PCs and deposit to a central location. Thursday, August 25, 2011 5:17 AM (permalink)
                      0
                      Here is an updated version that provides more error checking and better comments:
                       
                      '========== Variables.
                      Const ForAppending = 8
                      dtmThisDay = Day(Now)
                      dtmThisMonth = Month(Now)
                      dtmThisYear = Year(Now)
                      strDate = dtmThisYear & "_" & dtmThisMonth & "_" & dtmThisDay
                      strBackupName = strDate & "_"
                      Set objFSO = CreateObject("Scripting.FileSystemObject")

                      '========== Creates folder on syslog server to deposit backup logs.
                      If objFSO.FolderExists("E:\logs\evtlogs\" & strDate) Then
                          Set objFolder = objFSO.GetFolder("E:\logs\evtlogs\" & strDate)
                      Else
                          objFSO.CreateFolder("E:\logs\evtlogs\" & strDate)
                      End If

                      '========== Opens list of computers for remote connection.
                      Const ForReading = 1
                      Set objFile = objFSO.OpenTextFile("C:\scripts\computers.txt")
                      '======================================================================================================================================
                      '=== A Loop that will either connect to remote machines from the list, create a backup folder, back up and clear event logs 
                      '=== and then move the backups to the syslog server OR generate an error log with data concerning the failed connection.
                      '======================================================================================================================================
                      Do Until objFile.AtEndOfStream
                          strComputer = objFile.ReadLine
                      '28
                          '========== Attempts connection to remote machine from list.
                          On Error Resume Next
                          Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate,(Backup, Security)}!\\" & strComputer & "\root\cimv2")   
                          If Err.Number = 0 Then 
                       
                              '========== Creates c:\logs on remote machine
                              strInfoDir = "\\" & strComputer & "\C$\logs\" 
                              If Not objFSO.FolderExists(strInfoDir) Then
                                  objFSO.CreateFolder(strInfoDir)
                              End If    
                      '====== Backs up four log files to c:\logs\ and names them based on variables then clears the logs ====================================
                              Set colLogFiles = objWMIService.ExecQuery ("SELECT * FROM Win32_NTEventLogFile where LogFileName='Application'")
                              For Each objLogfile in colLogFiles
                                  objLogFile.BackupEventLog("c:\logs\" & strBackupName & strComputer & "_application.evt")
                                  'objLogFile.ClearEventLog()
                              Next 
                              Set colLogFiles = objWMIService.ExecQuery ("SELECT * FROM Win32_NTEventLogFile where LogFileName='Security'")
                              For Each objLogfile in colLogFiles
                                  objLogFile.BackupEventLog("c:\logs\" & strBackupName & strComputer & "_security.evt")
                                  'objLogFile.ClearEventLog()
                              Next
                              Set colLogFiles = objWMIService.ExecQuery ("SELECT * FROM Win32_NTEventLogFile where LogFileName='System'")
                              For Each objLogfile in colLogFiles
                                  objLogFile.BackupEventLog("c:\logs\" & strBackupName & strComputer & "_system.evt")
                                  'objLogFile.ClearEventLog()
                              Next
                      '57
                              Set colLogFiles = objWMIService.ExecQuery ("SELECT * FROM Win32_NTEventLogFile where LogFileName='Tumbleweed'")
                              For Each objLogfile in colLogFiles
                                  objLogFile.BackupEventLog("c:\logs\" & strBackupName & strComputer & "_tumbleweed.evt")
                                  'objLogFile.ClearEventLog()
                              Next
                      '===========================================================================================================
                              '========== Moves files to syslog server or writes error info to error log.  
                              strRemoteFile = "\\syslog server IP\e$\logs\evtlogs\" & strDate
                              On Error Resume Next 
                              objFSO.MoveFile "\\" & strComputer & "\C$\logs\*.evt", strRemoteFile
                           
                              If Err.Number <> 0 Then 
                                  bError = true
                                  Set objLogFile = objFSO.OpenTextFile("E:\logs\evtlogs\" & strDate & "_Error Log.txt", ForAppending, True)
                                  objLogFile.Write "Error moving files from " & strComputer & ": " & Err.Description & "."
                                  objLogFile.Writeline
                                  objLogFile.Close
                              End If
                              On Error Goto 0 
                          Else
                              bError = true
                           
                              Set objLogFile = objFSO.OpenTextFile("E:\logs\evtlogs\" & strDate & "_Error Log.txt", ForAppending, True) 
                              objLogFile.Write "No connection to " & strComputer & ": " & Err.Description & "." 
                              objLogFile.Writeline
                              objLogFile.Close 
                          End If
                          On Error Goto 0
                      '86
                      Loop
                      '======================================================================================================================================
                      '====================================================================================================================================== 
                      objFile.Close
                      '========== Popup window that lets sysadmin know if error logs were generated or not.
                      If bError <> 0 Then
                          Wscript.Echo "Logfile backup is complete. Please check the error logs."   
                      Else
                          Wscript.Echo "Logfile backup is complete."
                      End If
                       
                       
                      Enjoy!
                      <message edited by mtw999 on Thursday, August 25, 2011 5:49 AM>
                       
                      #11
                        59cobalt

                        • Total Posts : 979
                        • Scores: 91
                        • Reward points : 0
                        • Joined: 7/17/2011
                        • Status: offline
                        Re:Script to collect & clear event logs from remote PCs and deposit to a central location. Monday, August 29, 2011 10:12 AM (permalink)
                        0
                        FWIW, depending on which Windows version the OP has and how the actual environment looks like, event forwarding might be a better solution to the problem. This feature is available starting with Windows Vista and Server 2008.
                         
                        #12

                          Online Bookmarks Sharing: Share/Bookmark

                          Jump to:

                          Current active users

                          There are 0 members and 1 guests.

                          Icon Legend and Permission

                          • New Messages
                          • No New Messages
                          • Hot Topic w/ New Messages
                          • Hot Topic w/o New Messages
                          • Locked w/ New Messages
                          • Locked w/o New Messages
                          • Read Message
                          • Post New Thread
                          • Reply to message
                          • Post New Poll
                          • Submit Vote
                          • Post reward post
                          • Delete my own posts
                          • Delete my own threads
                          • Rate post

                          2000-2012 ASPPlayground.NET Forum Version 3.9