Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Filtering Event Logs 1

Status
Not open for further replies.

gmagerr

Technical User
Aug 11, 2001
323
US
Hi Guys

I have this script I'm working on that will go through the security logs of our domain controllers and return event id 672 category account logon. Basically I need to filter the events so that the event is = 672, the user ID begins with an underscore _gmagerr for example and the pre-authentication type = 2. Here's what I have. It just gets event id 672. Another thing that would be cool is if it would only return new events. Thanks in advance.

Code:
'==========================================================================
' 
' NAME: Get EventID 672
' 
' AUTHOR: Guy Thomas Modified By Gene Magerr
' EMAIL: genemagerr@hotmail.com
'
' COMMENT:
'
' VERSION HISTORY:
' 1.0  09/21/07  Initial release
'
'==========================================================================
' VBScript Prefix Naming Standard
'==========================================================================
' arr   Array       Contains an array of variables.
' bln   Boolean     Can contain either True or False
' byt   Byte        Integer value in the range of 0 to 255.
' col   Collection  Technically, a collection is not a variable subtype. 
'                   It is mentioned in this table because it is good 
'                   practice to use the col  prefix to indicate a collection. 
'                   Collections are used extensively in system administration
'                   scripts.
' (None)Constant    Constant values contain no prefix and use UPPER Case
'                   letters with underscores. Constants cannot be altered
'                   like normal variables.
' cur   Currency    Range of -922,337,203,685,477.5808 to 
'                   922,337,203,685,477.5807
' dbl   Double      Contains a double-precision floating-point number in 
'                   the range
' dic   Dictionary  Scripting dictionaries
' dtm   Date (Time) either a Date, Time, or Date and Time
' err   Error       Contains an error number value.
' fun   Functions   Programatic Function
' g_    Globals     Variables with global scope
' int   Integer     Contains integer value in the range of -32,768 to 32,767.
' lng   Long        Contains an integer value in the range -2,147,483,648 To
'                   2,147,483,647.
' obj   Object      Contains a reference to an Object.
' sng   Single      Contains a single-precision floating-point number 
' str   String      A variable length string of textual data
' sub   Subroutines Programatting SubRouting
' var   Variant     A variable that can store different data types at 
'                   different times.
'==========================================================================
' VARIABLE DECLARATIONS
'==========================================================================
Option Explicit

Dim objFso, objFolder, objWMI, objEvent, objTextFile, dtmEventDate ' Objects
Dim strFile, strComputer, strFolder, strFileName, strPath, strTimeWritten ' Strings
Dim intEvent, intNumberID, intRecordNum, colLoggedEvents, objEmail

'==========================================================================
' STATIC VARIABLE ASSIGNMENTS
'==========================================================================


'==========================================================================
' MAIN SCRIPT CODE
'==========================================================================
intNumberID = 672 ' Event ID Number
intEvent = 1
intRecordNum = 1

strFileName = "\Event672.txt"
strFolder = "C:\GeneTest"
strPath = strFolder & strFileName

Set objFso = CreateObject("Scripting.FileSystemObject")

If objFSO.FolderExists(strFolder) Then
    Set objFolder = objFSO.GetFolder(strFolder)
Else
   Set objFolder = objFSO.CreateFolder(strFolder)
   Wscript.Echo "Folder created " & strFolder
End If
Set strFile = objFso.CreateTextFile(strPath, True)

Const ForReading = 1

Set objTextFile = objFSO.OpenTextFile("C:\servers.txt", ForReading)

Do Until objTextFile.AtEndOfStream 
    strComputer = objTextFile.Readline

Set objWMI = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colLoggedEvents = objWMI.ExecQuery ("Select * from Win32_NTLogEvent Where Logfile = 'Security'" )

'Wscript.Echo " Press OK and Wait 30 seconds (ish)"
intEvent = 1
For Each objEvent in colLoggedEvents
If objEvent.EventCode = intNumberID Then

strFile.WriteLine ("Record No: ")& intEvent
strFile.WriteLine ("Category: " & objEvent.Category)
strFile.WriteLine ("Computer Name: " & objEvent.ComputerName)
strFile.WriteLine ("Event Code: " & objEvent.EventCode)
strFile.WriteLine ("Message: " & objEvent.Message)
strFile.WriteLine ("Record Number: " & objEvent.RecordNumber)
strFile.WriteLine ("Source Name: " & objEvent.SourceName)
'strFile.WriteLine ("Time Written: " & objEvent.TimeWritten)
dtmEventDate = objEvent.TimeWritten
strTimeWritten = WMIDateStringToDate(dtmEventDate)
strFile.WriteLine "Time Written: " & strTimeWritten
strFile.WriteLine ("Event Type: " & objEvent.Type)
strFile.WriteLine ("User: " & objEvent.User)
strFile.WriteLine (" ")
strFile.WriteLine ("===========================================================================")
strFile.WriteLine (" ")
intRecordNum = intRecordNum +1
End if
IntEvent = intEvent +1
Next
Wscript.Echo "Check " & strPath & " for " &intRecordNum & " events"

Loop
objTextFile.Close

Set objEmail = CreateObject("CDO.Message")
objEmail.From = "gmagerr@hotmail.com"
objEmail.To = "gmagerr@hotmail.com"
objEmail.Subject = strComputer & " EventID 672"
intEvent = 1
For Each objEvent in colLoggedEvents
If objEvent.EventCode = intNumberID Then
objEmail.TextBody = objEmail.TextBody & ("Record No: ")& intEvent & vbCrLf 
objEmail.TextBody = objEmail.TextBody & ("Category: " & objEvent.Category) & vbCrLf 
objEmail.TextBody = objEmail.TextBody & ("Computer Name: " & objEvent.ComputerName) & vbCrLf 
objEmail.TextBody = objEmail.TextBody & ("Event Code: " & objEvent.EventCode) & vbCrLf 
objEmail.TextBody = objEmail.TextBody & ("Message: " & objEvent.Message) & vbCrLf 
objEmail.TextBody = objEmail.TextBody & ("Record Number: " & objEvent.RecordNumber) & vbCrLf 
objEmail.TextBody = objEmail.TextBody & ("Source Name: " & objEvent.SourceName) & vbCrLf 
'objEmail.TextBody = objEmail.TextBody & ("Time Written: " & objEvent.TimeWritten) & vbCrLf 
dtmEventDate = objEvent.TimeWritten
strTimeWritten = WMIDateStringToDate(dtmEventDate)
objEmail.TextBody = objEmail.TextBody & ("Time Written: " & strTimeWritten) & vbCrLf 
objEmail.TextBody = objEmail.TextBody & ("Event Type: " & objEvent.Type) & vbCrLf 
objEmail.TextBody = objEmail.TextBody & ("User: " & objEvent.User) & vbCrLf 
objEmail.TextBody = objEmail.TextBody & (" ") & vbCrLf 
objEmail.TextBody = objEmail.TextBody & ("===========================================================================") & vbCrLf 
objEmail.TextBody = objEmail.TextBody & (" ") & vbCrLf 
intRecordNum = intRecordNum +1
End if
IntEvent = intEvent +1
Next

objEmail.Configuration.Fields.Item ("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/sendusing")[/URL] = 2
objEmail.Configuration.Fields.Item ("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/smtpserver")[/URL] = "smtp.server" 
objEmail.Configuration.Fields.Item ("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/smtpserverport")[/URL] = 25
objEmail.Configuration.Fields.Update
objEmail.Send

WScript.Quit

'==========================================================================
' SUBS AND FUNCTIONS
'==========================================================================
'==========================================================================
' This function will take the objEvent.TimeWritten which returns the time
' using WMI’s default Universal Time Coordinate format. In other words, 
' you’ll get back results similar to this: 20041025124000.000000-420
' and convert it to the proper date and time format
'==========================================================================
Function WMIDateStringToDate(dtmEventDate)

WMIDateStringToDate = CDate(Mid(dtmEventDate, 5, 2) & "/" & _
Mid(dtmEventDate, 7, 2) & "/" & Left(dtmEventDate, 4) _
& " " & Mid (dtmEventDate, 9, 2) & ":" & _
Mid(dtmEventDate, 11, 2) & ":" & Mid(dtmEventDate, 13, 2))

End Function
 
Wow i think that did it. Damn you guys are good. I really appreciate all of the input. i love this place.
 
dm4ever
is there a way to filter multiple fields? For example, say i want to get all of the underscore accounts with the Pre-Authentication Type: 2 how would I do that? or underscore accounts with an IP address of 10.1.x.x? thanks again for the help.
 
You might try this pattern:

"User ID:.+\\_.+Pre-Authentication Type:\s+[2]"

--------------------------------------------------------------------------------
dm4ever
My philosophy: K.I.S.S - Keep It Simple Stupid
 
Hmmm now I'm getting an error

Line: 123
Char: 1
Error: 0x80041021
Code: 80041021
Source: (null)

Line 123 is the Set objWMI line. Also email is not being sent to me, it was before. I have two domain controllers in the servers.txt file. Sorry about posting the code again, but it is changing.

Code:
'==========================================================================
' 
' SCRIPT NAME: EventID 672 Security.vbs
' 
' AUTHOR: Gene Magerr
' EMAIL: genemagerr@hotmail.com
'
' COMMENT: Original script by Guy Thomas, Modified by Gene Magerr
'
' VERSION HISTORY:
' 1.0   09/22/07  Initial release
'
'==========================================================================
' VBScript Prefix Naming Standard
'==========================================================================
' arr = Array		Contains an array of variables.
' bln = Boolean     Can contain either True or False
' byt = Byte        Integer value in the range of 0 to 255.
' col = Collection  Technically, a collection is not a variable subtype. 
'                   It is mentioned in this table because it is good 
'                   practice to use the col  prefix to indicate a collection. 
'                   Collections are used extensively in system administration
'                   scripts.
' Constant     		Constant values contain no prefix and use UPPER Case
'                   letters with underscores. Constants cannot be altered
'                   like normal variables.
' cur = Currency    Range of -922,337,203,685,477.5808 to 
'                   922,337,203,685,477.5807
' dbl = Double      Contains a double-precision floating-point number in 
' dic = Dictionary  Scripting dictionaries the range
' dtm = Date (Time) either a Date, Time, or Date and Time
' fun = Functions   Programatic Function
' err = Error       Contains an error number value.
' int = Integer     Contains integer value in the range of -32,768 to 32,767.
' lng = Long        Contains an integer value in the range -2,147,483,648 To
'                   2,147,483,647.
' obj = Object      Contains a reference to an Object.
' sng = Single      Contains a single-precision floating-point number 
' str = String      A variable length string of textual data
' sub = Subroutines Programatting SubRouting
' var = Variant     A variable that can store different data types at 
'                   different times.
' Wsh = Object		Windows Scripting Host Object
' g_  = Globals     Variables with global scope
'==========================================================================
Option Explicit

'==========================================================================
' If testmode is set to true, all wscript.echo messages will be displayed,
' if set to False no messages are displayed
' If SendMail is set to true, email will be sent, if set to False no email
' will be sent.
'==========================================================================
TestMode = False
SendMail = True

'==========================================================================
' VARIABLE DECLARATIONS
'==========================================================================
Dim WshShell, WshNetwork, objFSO, objFolder, objFile, objWMI, objEvent
Dim dtmEventDate, strTimeWritten, strServers, SendMail
Dim strComputer, strFileName, strFile, strFolder, strPath, TestMode
Dim intEvent, intNumberID, intRecordNum, colLoggedEvents, objEmail

Dim RegEx : Set RegEx = New RegExp
RegEx.Pattern = "User ID:.+\\_.+"
RegEx.IgnoreCase = True
RegEx.Global = True

Set WshShell = CreateObject("WScript.Shell")
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set objFSO = CreateObject("Scripting.FilesystemObject")

'==========================================================================
' STATIC VARIABLE ASSIGNMENTS
'==========================================================================
Const ForReading = 1

'==========================================================================
' MAIN SCRIPT CODE
'==========================================================================
strComputer = "."
strFileName = "\Event672.txt"
strFolder = "C:\logs"
strPath = strFolder & strFileName

' Set numbers
intNumberID = 672 ' Event ID Number
intRecordNum = 0


If objFSO.FolderExists(strFolder) Then
Set objFolder = objFSO.GetFolder(strFolder)
Else
Set objFolder = objFSO.CreateFolder(strFolder)
If TestMode = True Then
WScript.Echo "Just created " & strFolder
End If
End If

If objFSO.FileExists(strFolder & strFileName) Then
Set objFolder = objFSO.GetFolder(strFolder)
Else
Set objFile = objFSO.CreateTextFile(strFolder & strFileName)
If TestMode = True Then
WScript.Echo "Just created " & strFolder & strFileName
End If
End If 

Set objFile = Nothing
Set objFolder = Nothing

If TestMode = True Then
Wscript.Echo " Press OK and Wait 30 seconds (ish)"
End If
Set strFile = objFSO.CreateTextFile(strPath, True)

Set strServers = objFSO.OpenTextFile("C:\servers.txt", ForReading)

Do Until strServers.AtEndOfStream 
    strComputer = strServers.ReadLine
    

Set objWMI = GetObject("winmgmts:" & "{impersonationLevel=impersonate,(Security)}!\\" & strComputer & "\root\cimv2")
Set colLoggedEvents = objWMI.ExecQuery ("Select * from Win32_NTLogEvent Where Logfile = 'Security' And EventCode='672'")
For Each objEvent in colLoggedEvents
   		If RegEx.Test(objEvent.Message) Then
	            strFile.WriteLine("Category: " & objEvent.Category)
	            strFile.WriteLine("ComputerName: " & objEvent.ComputerName)
	            strFile.WriteLine("Logfile: " & objEvent.Logfile)
	            strFile.WriteLine("EventCode: " & objEvent.EventCode)
	            strFile.WriteLine("Message: " & objEvent.Message)
	            strFile.WriteLine("Record Number: " & objEvent.RecordNumber)
	            strFile.WriteLine("Source Name: " & objEvent.SourceName)
	            dtmEventDate = objEvent.TimeWritten
	            strTimeWritten = WMIDateStringToDate(dtmEventDate)
	            strFile.WriteLine "Time Written: " & strTimeWritten
	            strFile.WriteLine("EventType: " & objEvent.EventType)
	            strFile.WriteLine("User: " & objEvent.User)
	            strFile.WriteLine(" ")
	            strFile.WriteLine("===========================================================================")
	            strFile.WriteLine(" ")
	            intRecordNum = intRecordNum +1
   		End If
Next
If TestMode = True Then
WScript.Echo "Check " & strPath & " for " & intRecordNum & " events"
End If
Loop

strServers.Close

If SendMail = True Then

Set objEmail = CreateObject("CDO.Message")
objEmail.From = "gmagerr@mydomain.com"
objEmail.To = "gmagerr@mydomain.com"
objEmail.Subject = strComputer & " EventID 672"
'intEvent = 1
For Each objEvent in colLoggedEvents
	'If objEvent.EventCode = intNumberID Then
		objEmail.TextBody = objEmail.TextBody & ("Category: " & objEvent.Category) & vbCrLf 
		objEmail.TextBody = objEmail.TextBody & ("Computer Name: " & objEvent.ComputerName) & vbCrLf 
		objEmail.TextBody = objEmail.TextBody & ("Event Code: " & objEvent.EventCode) & vbCrLf 
		objEmail.TextBody = objEmail.TextBody & ("Message: " & objEvent.Message) & vbCrLf 
		objEmail.TextBody = objEmail.TextBody & ("Record Number: " & objEvent.RecordNumber) & vbCrLf 
		objEmail.TextBody = objEmail.TextBody & ("Source Name: " & objEvent.SourceName) & vbCrLf 
		dtmEventDate = objEvent.TimeWritten
		strTimeWritten = WMIDateStringToDate(dtmEventDate)
		objEmail.TextBody = objEmail.TextBody & ("Time Written: " & strTimeWritten) & vbCrLf 
		objEmail.TextBody = objEmail.TextBody & ("Event Type: " & objEvent.Type) & vbCrLf
		objEmail.TextBody = objEmail.TextBody & ("User: " & objEvent.User) & vbCrLf 
		objEmail.TextBody = objEmail.TextBody & (" ") & vbCrLf 
		objEmail.TextBody = objEmail.TextBody & ("===========================================================================") & vbCrLf 
		objEmail.TextBody = objEmail.TextBody & (" ") & vbCrLf 
		intRecordNum = intRecordNum +1
	'End if
Next

objEmail.Configuration.Fields.Item ("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/sendusing")[/URL] = 2
objEmail.Configuration.Fields.Item ("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/smtpserver")[/URL] = "mail.mydomain.com" 
objEmail.Configuration.Fields.Item ("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/smtpserverport")[/URL] = 25
objEmail.Configuration.Fields.Update
objEmail.Send

End If

'==========================================================================
' SUBS AND FUNCTIONS
'==========================================================================
'==========================================================================
' This function will take the objEvent.TimeWritten which returns the time
' using WMI’s default Universal Time Coordinate format. In other words, 
' you’ll get back results similar to this: 20041025124000.000000-420
' and convert it to the proper date and time format
'==========================================================================
Function WMIDateStringToDate(dtmEventDate)

WMIDateStringToDate = CDate(Mid(dtmEventDate, 5, 2) & "/" & _
Mid(dtmEventDate, 7, 2) & "/" & Left(dtmEventDate, 4) _
& " " & Mid (dtmEventDate, 9, 2) & ":" & _
Mid(dtmEventDate, 11, 2) & ":" & Mid(dtmEventDate, 13, 2))

End Function

WScript.Quit
 
winmgmts:" & "{impersonationLevel=impersonate,(Security)}!\\" & strComputer & "\root\cimv2"

You don't need that first &

"winmgmts:{impersonationLevel=impersonate,(Security)}!\\" & strComputer & "\root\cimv2"

Does the text file contain a blank line? If so, then that could explain the error.

Maybe

Do Until strServers.AtEndOfStream
strComputer = strServers.ReadLine
If strComputer <> "" Then
...code
End If
Loop

--------------------------------------------------------------------------------
dm4ever
My philosophy: K.I.S.S - Keep It Simple Stupid
 
Cool that was it, there was a couple empty lines after the last entry. The email portion is not working for some reason. I moved wscript.quit up to here. Is there a better way to compose that email other than going through all of the objects again?

Thanks.

Code:
Next

objEmail.Configuration.Fields.Item ("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/sendusing")[/URL] = 2
objEmail.Configuration.Fields.Item ("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/smtpserver")[/URL] = "mail.rand.org" 
objEmail.Configuration.Fields.Item ("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/smtpserverport")[/URL] = 25
objEmail.Configuration.Fields.Update
objEmail.Send

End If
WScript.Quit
 
I'd break the e-mail part into its own Sub or Function and call it when you need to send an e-mail.

Sub EMail(strText)
Set objEmail = CreateObject("CDO.Message")
...code
objEmail.TextBody = strText
...code
objEmail.Send
End Sub

Build a string in your For Each...Next section to build the body and then just send that to this Sub.

--------------------------------------------------------------------------------
dm4ever
My philosophy: K.I.S.S - Keep It Simple Stupid
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top