Tuesday, September 24, 2013

Restart a service checking a pattern in the event log

Restart a service checking a pattern in the event log and sending an e-mail to the xxxx@xxxx.com.

                                                                     
                                                                     
                                                                     
                                             

' ----- ExeScript Options Begin -----
' ScriptType: window,activescript,administrator
' DestDirectory: current
' CommandLine: -c 112 -p "3 / 10" -l Application -e "1 / 10"
' Icon: default
' 32Bit: yes
' Author: Babu Dhinakaran S
' ----- ExeScript Options End -----
'On Error Resume Next
Dim subStr
Dim Return1,Return2
Const CONVERT_TO_LOCAL_TIME = True
Dim strServiceName
Dim eCode
Dim patternMatch
Dim logFile
Dim aeCode, apatternMatch, alogFile
Dim dtmStartDate
Dim Flag

aeCode = Wscript.Arguments.Item(0)
eCode = CInt(Wscript.Arguments.Item(1))
apatternMatch = Wscript.Arguments.Item(2)
patternMatch = Wscript.Arguments.Item(3)
alogFile = Wscript.Arguments.Item(4)
logFile = Wscript.Arguments.Item(5)
aerrorPattern = Wscript.Arguments.Item(6)
errorPattern = Wscript.Arguments.Item(7)

'Wscript.Echo "aeCode"&aeCode
'Wscript.Echo "eCode"&eCode
'Wscript.Echo "apatternMatch"&apatternMatch
'Wscript.Echo "alogFile"&alogFile
'Wscript.Echo "logFile"&logFile
'Wscript.Echo "aerrorPattern"&aerrorPattern
'Wscript.Echo "errorPattern"&errorPattern

If aeCode = "-c" and apatternMatch = "-p" and alogFile = "-l" and aerrorPattern = "-e" Then
 Set objFSO = CreateObject("Scripting.FileSystemObject")
 fileName = "C:\Program Files\NSClient++\scripts\" & logFile & "_ "& ecode & ".txt"
 fileName2 = "C:\Program Files\NSClient++\scripts\" & logFile & "_ "& ecode & "_flag"&".txt"
 'Wscript.Echo "FileName:" & fileName

 'The Below File or fileName variable holds the TimeStamp of the EventLog

 If objFSO.FileExists(fileName) Then
  'Wscript.Echo "File Exists"
  Set objTextFile = objFSO.OpenTextFile(fileName, 1)
  Do Until objTextFile.AtEndOfStream
  dtmStartDate = objTextFile.Readline
  'Wscript.Echo " DtmStartDate:" & dtmStartDate
  
  Loop

 Else 
  Set objTextFile = objFSO.CreateTextFile(fileName, true)
  Set dtmStartDate = CreateObject("WbemScripting.SWbemDateTime")
  dtmStartDate.SetVarDate (CDate (now))
  'Wscript.Echo "File Doesn't exists create one"
  objTextFile.WriteLine(dtmStartDate)
  'Wscript.Echo " DtmStartDate:" & dtmStartDate
  'objTextFile.Close()
 End If


 'The below file holds the Flag value and initially the flag is set to 0 stating there were no error found

 If objFSO.FileExists(fileName2) Then
  'Wscript.Echo "File Exists"
  Set objTextFile1 = objFSO.OpenTextFile(fileName2, 1)
  Do Until objTextFile1.AtEndOfStream
  flag = CInt(objTextFile1.Readline)
  'Wscript.Echo "File Exists:" & flag
  
  Loop

 Else 
  Set objTextFile1 = objFSO.CreateTextFile(fileName2, true)
  'Wscript.Echo "File Doesn't exists create one and set falg to 0"
  objTextFile1.WriteLine("0")
  'objTextFile1.Close()
 End If



 strComputer = "."
 Set objWMIService = GetObject("winmgmts:" _
  & "{impersonationLevel=impersonate,(Security)}!\\" _
  & strComputer & "\root\cimv2")
 'Set the event code in the below WMI Query such as 112 or 113

 Set colEvents = objWMIService.ExecQuery _
  ("Select * from Win32_NTLogEvent Where Logfile = '" & logFile & "' and " & " TimeWritten > ' " & dtmStartDate & " ' and EventCode=" & eCode & "") 
  
  

 'Wscript.Echo logFile
 'Wscript.Echo eCode
 'Wscript.Echo dtmStartDate
 If Err.Number <> 0 Then

  'WScript.Echo "Error: " & Err.Number
  'WScript.Echo "Error (Hex): " & Hex(Err.Number)
  'WScript.Echo "Source: " &  Err.Source
  'WScript.Echo "Description: " &  Err.Description
  Err.Clear
  Wscript.Echo "Unable to Access the remote Server"
  Wscript.Quit(3)
 
    Else
      

  
   If flag = 0 Then 
   
     For each objEvent in colEvents
   'Wscript.Echo "Category: " & objEvent.Category
   'Wscript.Echo "Computer Name: " & objEvent.ComputerName
   'Wscript.Echo "Event Code: " & objEvent.EventCode
   'Wscript.Echo "Message: " & objEvent.Message

    subStr = objEvent.Message
    'Wscript.Echo "Message:" & subStr
   'Wscript.Echo "Record Number: " & objEvent.RecordNumber
   'Wscript.Echo "Source Name: " & objEvent.SourceName
   'Wscript.Echo "Time Written: " & objEvent.TimeWritten
   'Wscript.Echo "Event Type: " & objEvent.Type
   'Wscript.Echo "User: " & objEvent.User
   'Wscript.Echo objEvent.LogFile

   'Prepare a regular expression object
    strServiceName = objEvent.SourceName
    dateWritten = objEvent.TimeWritten
    'Wscript.Echo "Date Written:" & dateWritten
   
   
    Set myRegExp = New RegExp 
    myRegExp.IgnoreCase = True
    myRegExp.Global = True
     myRegExp.Pattern = errorPattern
   'Wscript.Echo "errorPattern:" & errorPattern
   ' Echo for each match
    Set myMatches = myRegExp.Execute(subStr)
    If myMatches.count > 0 Then
           
         
    'Wscript.Echo "Service will be restarted:" &strServiceName 
   
    'Set the New Time Stamp 
    Set objTextFile = objFSO.CreateTextFile(fileName, true)
    'Set dtmStartDate = CreateObject("WbemScripting.SWbemDateTime")
    'dtmStartDate.SetVarDate (dateWritten)
    'Wscript.Echo "ErrorPattern Date:" & dateWritten
    objTextFile.WriteLine(dateWritten)
    'objTextFile.Close()
   
    'Set the New Flag 1 if a match is found for errorPattern
    Set objTextFile1 = objFSO.CreateTextFile(fileName2, true)
    'Wscript.Echo "File Doesn't exists create one"
    objTextFile1.WriteLine("1")
    'objTextFile1.Close()
       Wscript.Echo "System has entered in CRITICAL State of /10"
    'For Each myMatch in myMatches
    '  Wscript.Echo myMatch.Value, "Found Match"
    '  Wscript.Echo "---------------------------------------------------------------"
    ' Next 
    Wscript.Quit(2)
    
         Else 
    'don't do anything let it to loop till the match
    
   End If
   Next
       Wscript.Echo "System has not entered in CRITICAL State of /10"
    Wscript.Quit(0)
          End If 
    
          If flag = 1 Then 
    
     For each objEvent in colEvents
    'Wscript.Echo "Category: " & objEvent.Category
    'Wscript.Echo "Computer Name: " & objEvent.ComputerName
    'Wscript.Echo "Event Code: " & objEvent.EventCode
    'Wscript.Echo "Message: " & objEvent.Message

    subStr = objEvent.Message
    'Wscript.Echo "Message:" & subStr
    'Wscript.Echo "Record Number: " & objEvent.RecordNumber
    'Wscript.Echo "Source Name: " & objEvent.SourceName
    'Wscript.Echo "Time Written: " & objEvent.TimeWritten
    'Wscript.Echo "Event Type: " & objEvent.Type
    'Wscript.Echo "User: " & objEvent.User
    'Wscript.Echo objEvent.LogFile

    'Prepare a regular expression object
    strServiceName = objEvent.SourceName
    dateWritten = objEvent.TimeWritten
    'Wscript.Echo "Date Written:" & dateWritten
   
    Set myRegExp = New RegExp 
    myRegExp.IgnoreCase = True
    myRegExp.Global = True
    myRegExp.Pattern = patternMatch
    'Wscript.Echo "Pattern Match:" & patternMatch
    ' Echo for each match
    Set myMatches = myRegExp.Execute(subStr)
       If myMatches.count > 0 Then
                        
    'Set the New Time Stamp 
    Set objTextFile = objFSO.CreateTextFile(fileName, true)
    'Set dtmStartDate = CreateObject("WbemScripting.SWbemDateTime")
    'dtmStartDate.SetVarDate (dateWritten)
    'Wscript.Echo "Pattern Date:" & dateWritten
    objTextFile.WriteLine(dateWritten)
    'objTextFile.Close()
   
    'Set the New Flag 0 if a match is found for patternMatch
    Set objTextFile1 = objFSO.CreateTextFile(fileName2, true)
    objTextFile1.WriteLine("0")
    'objTextFile1.Close()
    
    'For Each myMatch in myMatches
     'Wscript.Echo myMatch.Value, "Found Match"
     'Wscript.Echo "---------------------------------------------------------------"
     'Next 
       
    'Restart the Service and Send an successful or unsccessful message accordingly
    Set objMessage = CreateObject("CDO.Message")
    objMessage.From = "no-reply@cmcmarkets.com" 
    objMessage.To = "b.dhinakaran@cmcmarkets.com" 
    objMessage.Cc = "t.welsh@cmcmarkets.com"
    objMessage.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    objMessage.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.cmc.local"
    objMessage.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
    objMessage.Configuration.Fields.Update

    Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
     Set colListOfServices = objWMIService.ExecQuery("Select * from Win32_Service Where Name ='" & strServiceName & "'") 
           
     If Err.Number <> 0 Then

      'WScript.Echo "Error: " & Err.Number
      'WScript.Echo "Error (Hex): " & Hex(Err.Number)
      'WScript.Echo "Source: " &  Err.Source
      'WScript.Echo "Description: " &  Err.Description
      Err.Clear
      objMessage.Subject = "Unable to invoke object to restart the service:" & strServiceName
      mailbody = "Please check to why this was not restarted automatically or manually restart the Service"
      objMessage.TextBody = mailbody
      objMessage.Send
      Wscript.Quit(3)

     Else
      'Stop Service
      For Each objService in colListOfServices
       Return1 = objService.StopService()
         If Return1 <> 0 Then
          'Wscript.Echo "Failed to Stop the Service and the Error code = " & Return1                                  
          objMessage.Subject = "Service didn't respond for Stop Signal:" & strServiceName
          mailbody = "Please check to why this was not restarted automatically or manually restart the Service"
          objMessage.TextBody = mailbody
          objMessage.Send
          Wscript.Quit(2)
         End If       
      Next

     Wscript.Sleep(20000)        'Sleep for 20 seconds before starting a service.

      'Start Service

      For Each objService in colListOfServices
       Return2 = objService.StartService()
         If Return2 <> 0 Then
          Wscript.Echo "Failed to Start the Service and the Error code = " & Return2 
          objMessage.Subject = "Service didn't respond for Start Signal after the Stop:" & strServiceName
          mailbody = "Please check to why this was not restarted automatically or manually restart the Service"
          objMessage.TextBody = mailbody
          objMessage.Send
          Wscript.Quit(2)
         Else
        
             WScript.Echo "Successful Restart of Service:" & strServiceName
          objMessage.Subject = "Successful Restart of Service:" & strServiceName
          mailbody = "Successful Restart of Service"
          objMessage.TextBody = mailbody
          objMessage.Send
         Wscript.Quit(0)

         End If

      Next
              
     End If
     
     
         Else 
        'Wscript.Echo "System has entered in CRITICAL State of /10"
     'Wscript.Quit(2) 
    
   End If
   Next
   Wscript.Echo "System has entered in CRITICAL State of /10"
   Wscript.Quit(2)
   End If
       
       
      
  End If

Else  
Wscript.Echo "Follow the Syntax: example: eventlog -c EventCode -p Pattern_to_Match_in_the_message_to_service_restart -l logfile_Application_System -e errorPattern_to_Match _in_then_message_to_trigger_an_alarm"  
End If  

No comments:

Post a Comment