Reading the Windows Eventlog with a Perl Script

How to read Windows event log entries using a Perl script:  ActiveState ActivePerl comes with some Windows-specific modules that can come in handy.  Win32::EventLog is one of these.  We can use it to connect to a Windows event log and read through the events.  In this example, we'll point at a domain controller and find logon events so we can see who has authenticated against this domain controller recently.

Windows logon events can be via two different authentication protocols: Kerberos and NTLM.  When a user authenticates to the domain via Kerberos, a 672 event is generated, while a 680 event is generated during an NTLM logon.

The following script searches for these events, parses out the username and either the client IP address (Kerberos) or the client name (NTLM).  The script displays the newest event first, then goes backwards in time.

use Win32::EventLog;
$myServer="\\\\myDomainController";
$handle=Win32::EventLog->new("Security", $myServer);
$handle->GetNumber($numrecs);
$handle->GetOldest($oldest);
$newest = $oldest + $numrecs;
for ($x=$newest;$x>=$oldest;$x--){
 $handle->Read(EVENTLOG_FORWARDS_READ¦EVENTLOG_SEEK_READ,$x,$event);
 if(($event->{EventID} == 680) ¦¦ ($event->{EventID} == 672)){
  Win32::EventLog::GetMessageText($event);
  @message=split /\n/,$event->{Message};
  $dt=localtime($event->{TimeGenerated});
  foreach $line (@message){
   $line=~s/\s//g;
   ($name,$value)=split /:/,$line;
   if($name eq "Logonaccount"){ $user=$value; $authType = "NTLM"; }
   if($name eq "SourceWorkstation"){ $client=$value; }
   if($name eq "UserName"){ $user=$value; $authType = "Kerberos"; }
   if($name eq "ClientAddress"){ $client=$value; }
  }
  if(index($user,"\$") == -1){
   print "$dt\t$user\t$client\t($authType)\n";
  }
 }
}
$handle->Close;

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...