Thursday, April 17, 2014

script to kill a processes after 12 hours of run and send an e-mail with the resultant process List

'program to kill the process after 12 hours and send an e-mail with the process list other than the killed processes

'Below variable holds the process name as you see in the task manager
processName = "iexplore.exe"
'Below varaible holds the time range which can hold the values such as "h" for hours, "n" for minutes
timerange = "h"
'Below varaible kills the process with the time bound in relation with the timerange i.e., hours or minutes
killtime = 12
'From address, make sure the from address has rights to send an e-mail.
emailFrom = "xyz@abc.com"
'send an e-mail to primary recipent
emailTo = "asdf@abc.com"
'send an e-mail to secondary recipent
emailCC = "ghjkl@abc.com"
strComputer = "."
flag = 0
Set wshNetwork = WScript.CreateObject( "WScript.Network" )
strComputerName = wshNetwork.ComputerName

Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colProcessList = objWMIService.ExecQuery _
    ("Select * from Win32_Process Where Name = '" &processName& "'")

For Each objProcess in colProcessList
          dtmProcessCreationDate = objProcess.CreationDate
          WMIDateStringToDate = CDate(Mid(dtmProcessCreationDate, 5, 2) & "/" & _
     Mid(dtmProcessCreationDate, 7, 2) & "/" & Left(dtmProcessCreationDate, 4) _
         & " " & Mid (dtmProcessCreationDate, 9, 2) & ":" & _
             Mid(dtmProcessCreationDate, 11, 2) & ":" & Mid(dtmProcessCreationDate, _
                 13, 2))
          timeElapsed = DateDiff(timerange,WMIDateStringToDate,now)
          'WScript.Echo objProcess.Caption
          'WScript.Echo WMIDateStringToDate
          'WScript.Echo Now
          'WScript.Echo "Time Elapsed:" & timeElapsed
         
          If timeElapsed > killtime Then
    preturn = objProcess.Terminate()
          If preturn = 0 Then
          pstatus = "Successful kill of the process:"
                   pid = objProcess.ProcessId
                   filepath = writeprocess()
          Call sendmail(pstatus,pid,filepath)
          End If
          If preturn = 2 Then
          pstatus = "Access Denied"
                   pid = objProcess.ProcessId
                   filepath = writeprocess()
          Call sendmail(pstatus,pid,filepath)
          End If
          If preturn = 3 Then
          pstatus = "Insufficient Privilege"
                   pid = objProcess.ProcessId
                   filepath = writeprocess()
          Call sendmail(pstatus,pid,filepath)
          End If
          If preturn = 8 Then
          pstatus = "Unknown Failure"
                   pid = objProcess.ProcessId
                   filepath = writeprocess()
          Call sendmail(pstatus,pid,filepath)
          End If
          If preturn = 9 Then
          pstatus = "Path Not Found"
                   pid = objProcess.ProcessId
                   filepath = writeprocess()
          Call sendmail(pstatus,pid,filepath)
          End If
          If preturn = 21 Then
          pstatus = "Invalid Parameter"
                   pid = objProcess.ProcessId
                   filepath = writeprocess()
          Call sendmail(pstatus,pid,filepath)
          End If          
    End If
    
Next

Function writeprocess()
                   strProcessList = "" 

                   strProcessList = "<HTML>" &vbNewLine & "<BODY>" & "<TABLE border=" & "1" & " style="& "width:400px & " & ">" & "<TH>" & "ProcessName" & "</TH>" & "<TH>" & "ProcessOwner" & "</TH>" & "<TH>" & "ProcessID" & "</TH>" & vbNewLine

                   Set colProcessList = objWMIService.ExecQuery _
          ("Select * from Win32_Process Where Name <> '" & processName & "'")
   
                   For Each objProcess in colProcessList

                   Return = objProcess.GetOwner(strNameOfUser)
          If Return <> 0 Then
          strNameOfUser = "Unable to Fetch Owner info:" & Return
           'WScript.Echo "Could not get owner info for process " & objProcess.Name & VBNewLine & "Error = " & Return
          Else 
          'Wscript.Echo "Process " & objProcess.Name & " is owned by " & "\" & strNameOfUser & "."
          End If
          strProcessList = strProcessList & "<TR>" & vbNewLine
          strProcessList = strProcessList & "<TD>" & objProcess.Caption & "</TD>"
          strProcessList = strProcessList & "<TD>" & strNameOfUser & "</TD>"
          strProcessList = strProcessList & "<TD>" & objProcess.ProcessId & "</TD>"
          'strProcessList = strProcessList & objProcess.Caption & vbTab & strNameOfUser & vbTab & objProcess.PageFileUsage & vbNewLine
          strProcessList = strProcessList & "</TR>" & vbNewLine 
                   Next

                   strProcessList = strProcessList & "</TABLE></BODY>" &vbNewLine & "</HTML>" &vbNewLine
                   Dim objFSO 'As FileSystemObject
                   Dim objTextFile 'As Object
    
                    Const ForReading = 1
           Const ForWriting = 2
                    Const ForAppending = 8
    
                     Set objFSO = CreateObject("Scripting.FileSystemObject")
                     currentDirectory = objFSO.GetAbsolutePathName(".")
                     filePath = currentDirectory & "\processlist.html"
                     Set objTextFile = objFSO.CreateTextFile(filePath,2,True)
                     ' Write a line.
                     objTextFile.Write (strProcessList)
                     objTextFile.Close

                     'WScript.Echo strProcessList
                   writeprocess = filePath

End Function

Function sendmail(processStatus,ProcessId,filePath)

   Set objMessage = CreateObject("CDO.Message")
                             objMessage.From = emailFrom
                             objMessage.To = emailTo
                             objMessage.Cc = emailCC
                             objMessage.Configuration.Fields.Item _
                             ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
                             objMessage.Configuration.Fields.Item _
                             ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.abc.com"
                             objMessage.Configuration.Fields.Item _
                             ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 8181
                             objMessage.Configuration.Fields.Update

                             objMessage.Subject = processStatus & " for the process " & processName & " with Process ID " & ProcessId
                             mailbody = "Process List other than IE from ProcessPool is enclosed" & vbNewLine
                             objMessage.AddAttachment filePath
                             objMessage.TextBody = mailbody
                             objMessage.Send
End Function

No comments:

Post a Comment