home *** CD-ROM | disk | FTP | other *** search
/ Chip: Windows 2000 Professional Resource Kit / W2KPRK.iso / apps / perl / ActivePerl.exe / data.z / EventLog.pm < prev    next >
Encoding:
Perl POD Document  |  1999-10-14  |  14.7 KB  |  554 lines

  1. #
  2. # EventLog.pm
  3. #
  4. # Creates an object oriented interface to the Windows NT Evenlog 
  5. # Written by Jesse Dougherty
  6. #
  7.  
  8. package Win32::EventLog;
  9.  
  10. use vars qw($VERSION);
  11.  
  12. $VERSION = '0.062';
  13.  
  14. require Exporter;
  15. require DynaLoader;
  16. #use Win32;
  17.  
  18. die "The Win32::Eventlog module works only on Windows NT"
  19.     unless Win32::IsWinNT();
  20.  
  21. @ISA= qw( Exporter DynaLoader );
  22. @EXPORT = qw(
  23.     EVENTLOG_AUDIT_FAILURE
  24.     EVENTLOG_AUDIT_SUCCESS
  25.     EVENTLOG_BACKWARDS_READ
  26.     EVENTLOG_END_ALL_PAIRED_EVENTS
  27.     EVENTLOG_END_PAIRED_EVENT
  28.     EVENTLOG_ERROR_TYPE
  29.     EVENTLOG_FORWARDS_READ
  30.     EVENTLOG_INFORMATION_TYPE
  31.     EVENTLOG_PAIRED_EVENT_ACTIVE
  32.     EVENTLOG_PAIRED_EVENT_INACTIVE
  33.     EVENTLOG_SEEK_READ
  34.     EVENTLOG_SEQUENTIAL_READ
  35.     EVENTLOG_START_PAIRED_EVENT
  36.     EVENTLOG_SUCCESS
  37.     EVENTLOG_WARNING_TYPE
  38. );
  39.  
  40. $GetMessageText=0;
  41.  
  42. sub AUTOLOAD {
  43.     my($constname);
  44.     ($constname = $AUTOLOAD) =~ s/.*:://;
  45.     # reset $! to zero to reset any current errors.
  46.     $!=0;
  47.     my $val = constant($constname, @_ ? $_[0] : 0);
  48.     if ($! != 0) {
  49.     if ($! =~ /Invalid/) {
  50.         $AutoLoader::AUTOLOAD = $AUTOLOAD;
  51.         goto &AutoLoader::AUTOLOAD;
  52.     }
  53.     else {
  54.         my ($pack,$file,$line) = caller;
  55.         die "Unknown Win32::EventLog macro $constname, at $file line $line.\n";
  56.     }
  57.     }
  58.     eval "sub $AUTOLOAD { $val }";
  59.     goto &$AUTOLOAD;
  60. }
  61.  
  62.  
  63. #
  64. # new()
  65. #
  66. #   Win32::EventLog->new("source name", "ServerName");
  67. #
  68. sub new {
  69.     my $c = shift;
  70.     die "usage: PACKAGE->new(SOURCENAME[, SERVERNAME])\n" unless @_;
  71.     my $source = shift;
  72.     my $server = shift;
  73.     my $handle;
  74.  
  75.     # Create new handle
  76.  
  77.     if ($source !~ /\\/) {
  78.     OpenEventLog($handle, $server, $source);
  79.     }    
  80.     else {
  81.     OpenBackupEventLog($handle,$server,$source);
  82.     }
  83.     return bless {
  84.           'handle' => $handle,
  85.           'Source' => $source,
  86.           'Computer' => $server
  87.          }, $c;
  88. }
  89.  
  90. sub DESTROY {
  91.     my $self = shift;
  92.     CloseEventLog($self->{'handle'});
  93. }
  94.  
  95. #
  96. # Open (the rather braindead old way)
  97. # A variable initialized to empty must be supplied as the first
  98. # arg, followed by whatever new() takes
  99. #
  100. sub Open {
  101.     $_[0] = Win32::EventLog->new($_[1],$_[2]);
  102. }
  103.  
  104. sub OpenBackup {
  105.     my $c=shift;
  106.     my $file=shift;
  107.     my $server=shift;
  108.     my $handle;
  109.  
  110.     OpenBackupEventLog($handle,$server,$file);
  111.     return bless {
  112.           'handle' => $handle,
  113.           'Source' => $file,
  114.           'Computer' => $server
  115.          }, $c;
  116. }
  117.  
  118. sub Backup {
  119.     $self = shift;
  120.     die " usage: OBJECT->Backup(FILENAME)\n" unless @_ == 1;
  121.     my $filename = shift;
  122.     my $result;
  123.  
  124.     $result = BackupEventLog($self->{'handle'},$filename);
  125.     unless ($result) {
  126.     $! = Win32::GetLastError();
  127.     }
  128.     return $result;
  129. }
  130.  
  131. sub Close {
  132.     my $self=shift;
  133.     CloseEventLog($self->{'handle'});
  134.     undef $self;
  135. }
  136.  
  137. # Read
  138. # Note: the EventInfo arguement requires a hash reference.
  139. sub Read {
  140.     $self = shift;
  141.  
  142.     die "usage: OBJECT->Read(FLAGS, RECORDOFFSET, HASHREF)\n" unless @_ == 3;
  143.  
  144.     my ($readflags,$recordoffset) = @_;
  145.     my ($result, $datalength, $dataoffset, $sid, $length);
  146.     my ($reserved, $recordnumber, $timegenerated, $timewritten, $eventid);
  147.     my ($eventtype, $numstrings, $eventcategory, $reservedflags);
  148.     my ($closingrecordnumber, $stringoffset, $usersidlength, $usersidoffset);
  149.  
  150.     # The following is stolen shamelessly from Wyt's tests for the registry. 
  151.  
  152.     $result = ReadEventLog($self->{'handle'},
  153.                $readflags,
  154.                $recordoffset,
  155.                $header,
  156.                $source,
  157.                $computer,
  158.                $sid,
  159.                $data,
  160.                $strings);
  161.  
  162.     ($length,
  163.      $reserved,
  164.      $recordnumber,
  165.      $timegenerated,
  166.      $timewritten,
  167.      $eventid,
  168.      $eventtype,
  169.      $numstrings,
  170.      $eventcategory,
  171.      $reservedflags,
  172.      $closingrecordnumber,
  173.      $stringoffset,
  174.      $usersidlength,
  175.      $usersidoffset,
  176.      $datalength,
  177.      $dataoffset) = unpack('l6s4l6', $header);
  178.  
  179.     # make a hash out of the values returned from ReadEventLog.
  180.     my %h = ( 'Source'            => $source,
  181.           'Computer'        => $computer,
  182.           'Length'            => $datalength,
  183.           'Category'        => $eventcategory,
  184.           'RecordNumber'        => $recordnumber,
  185.           'TimeGenerated'        => $timegenerated,
  186.           'Timewritten'        => $timewritten,
  187.           'EventID'            => $eventid,
  188.           'EventType'        => $eventtype,
  189.           'ClosingRecordNumber'    => $closingrecordnumber,
  190.           'User'            => $sid,
  191.           'Strings'            => $strings,
  192.           'Data'            => $data,
  193.         );
  194.     # get the text message here
  195.     my $message='';
  196.     if ($result and $GetMessageText) {
  197.     my $message;
  198.     GetEventLogText($source, $eventid, $strings, $numstrings, $message);
  199.     $h{Message}=$message;
  200.     }
  201.  
  202.     if (ref($_[2]) eq 'HASH') {
  203.     %{$_[2]} = %h;        # this needed for Read(...,\%foo) case
  204.     }
  205.     else {
  206.     $_[2] = \%h;
  207.     }
  208.     unless ($result) { $! = Win32::GetLastError() }
  209.     return $result;
  210. }
  211.  
  212. sub GetMessageText {
  213.     my $self = shift;
  214.     my $message;
  215.     GetEventLogText($self->{Source},
  216.             $self->{EventID},
  217.             $self->{Strings},
  218.             $self->{Strings}=~tr/\0/\0/,
  219.             $message);
  220.     $self->{Message}=$message;
  221.     return $message;
  222. }
  223.  
  224. sub Report {
  225.     my $self = shift;
  226.     
  227.     die "usage: OBJECT->Report( HASHREF )\n" unless @_ == 1;
  228.  
  229.     my $EventInfo = shift;
  230.     my $result;
  231.  
  232.     if (ref( $EventInfo)  eq "HASH") {
  233.     my ($length, $reserved, $recordnumber, $timegenerated, $timewritten);
  234.     my ($eventid, $eventtype, $numstrings, $eventcategory, $reservedflags);
  235.     my ($closingrecordnumber, $stringoffset, $usersidlength);
  236.     my ($usersidoffset, $source, $data, $strings);
  237.  
  238.     $eventcategory        = $EventInfo->{'Category'};
  239.     $source            = exists($EventInfo->{'Source'})
  240.                   ? $EventInfo->{'Source'}
  241.                   : $self->{'Source'};
  242.     $computer        = $EventInfo->{'Computer'}
  243.                   ? $EventInfo->{'Computer'}
  244.                   : $self->{'Computer'};
  245.     $length            = $EventInfo->{'Length'};
  246.     $recordnumber        = $EventInfo->{'RecordNumber'};
  247.     $timegenerated        = $EventInfo->{'TimeGenerated'};
  248.     $timewritten        = $EventInfo->{'Timewritten'};
  249.     $eventid        = $EventInfo->{'EventID'};
  250.     $eventtype        = $EventInfo->{'EventType'};
  251.     $closingrecordnumber    = $EventInfo->{'ClosingRecordNumber'};
  252.     $strings        = $EventInfo->{'Strings'};
  253.     $data            = $EventInfo->{'Data'};
  254.  
  255.     $result = WriteEventLog($computer,
  256.                 $source,
  257.                 $eventtype,
  258.                 $eventcategory,
  259.                 $eventid,
  260.                 $reserved,
  261.                 $data,
  262.                 $strings);
  263.     } 
  264.     else {
  265.     die "Win32::EventLog::Report requires a hash reference as arg 3\n";
  266.     }
  267.  
  268.     unless ($result) { $! = Win32::GetLastError() }
  269.     return $result;
  270. }
  271.  
  272. sub GetOldest {
  273.     my $self=shift;
  274.         
  275.     die "usage: OBJECT->GetOldest( SCALAREF )\n" unless @_ == 1;
  276.     my $result = GetOldestEventLogRecord( $self->{'handle'},$_[0]);
  277.     unless ($result) { $! = Win32::GetLastError() }
  278.     return $result;
  279. }
  280.  
  281. sub GetNumber {
  282.     my $self=shift;
  283.  
  284.     die "usage: OBJECT->GetNumber( SCALARREF )\n" unless @_ == 1;
  285.     my $result = GetNumberOfEventLogRecords($self->{'handle'}, $_[0]);
  286.     unless ($result) { $! = Win32::GetLastError() }
  287.     return $result;
  288. }
  289.  
  290. sub Clear {
  291.     my $self=shift;
  292.  
  293.     die "usage: OBJECT->Clear( FILENAME )\n" unless @_ == 1;
  294.     my $filename = shift;
  295.     my $result = ClearEventLog($self->{'handle'}, $filename);
  296.     unless ($result) { $! = Win32::GetLastError() }
  297.     return $result;
  298. }
  299.  
  300. bootstrap Win32::EventLog;
  301.  
  302. 1;
  303. __END__
  304.  
  305. =head1 NAME
  306.  
  307. Win32::EventLog - Process Win32 Event Logs from Perl
  308.  
  309. =head1 SYNOPSIS
  310.  
  311.     use Win32::EventLog
  312.     $handle=Win32::EventLog->new("Application");
  313.  
  314. =head1 DESCRIPTION
  315.  
  316. This module implements most of the functionality available from the
  317. Win32 API for accessing and manipulating Win32 Event Logs. The access
  318. to the EventLog routines is divided into those that relate to an
  319. EventLog object and its associated methods and those that relate other
  320. EventLog tasks (like adding an EventLog record).
  321.  
  322. =head1 The EventLog Object and its Methods
  323.  
  324. The following methods are available to open, read, close and backup
  325. EventLogs.
  326.  
  327. =over 4
  328.  
  329. =item Win32::EventLog->new(SOURCENAME [,SERVERNAME]); 
  330.  
  331. The B<new> method creates a new EventLog object and returns a handle to it. This
  332. hande is then used to call the methods below.
  333.  
  334. The method is overloaded in that if the supplied B<SOURCENAME> argument
  335. contains one or more literal '\' characters (an illegal character in a
  336. B<SOURCENAME>), it assumes that you are trying to open a backup
  337. eventlog and uses B<SOURCENAME> as the backup eventlog to open. Note
  338. that when opening a backup eventlog, the B<SERVERNAME> argument is
  339. ignored (as it is in the underlying Win32 API). For EventLogs on
  340. remote machines, the B<SOURCENAME> parameter must therefore be
  341. specified as a UNC path.
  342.  
  343. =item $handle->Backup(FILENAME);
  344.  
  345. The Backup() method backs up the EventLog represented by $handle. It
  346. takes a single arguemt, B<FILENAME>. When $handle represents an
  347. EventLog on a remote machine, B<FILENAME> is filename on the remote
  348. machine and cannot be a UNC path (i.e you must use C:\TEMP\App.EVT).
  349. The method will fail if the log file already exists.
  350.  
  351. =item $handle->Read(FLAGS, OFFSET, HASHREF);
  352.  
  353. The Read() method read an EventLog entry from the EventLog represented
  354. by $handle.
  355.  
  356. =item $handle->Close();
  357.  
  358. The Close() method closes the EventLog represented by $handle. After
  359. B<Close> has been called, any further attempt to use the EventLog
  360. represented by $handle will fail.
  361.  
  362. =item $handle->GetOldest(SCALARREF);
  363.  
  364. The I<GetOldest()> method number of the the oldest EventLog record in
  365. the EventLog represented by $handle. This is required to correctly
  366. compute the B<OFFSET> required by the $handle->Read() method.
  367.  
  368. =item $handle->GetNumber(SCALARREF);
  369.  
  370. The I<GetNumber()> method returns the number of EventLog records in
  371. the EventLog represented by $handle. The number of the most recent
  372. record in the EventLog is therefore computed by
  373.  
  374. =over 4
  375.  
  376. $handle->GetOldest($oldest);
  377. $handle->GetNumber($lastRec);
  378. $lastRecOffset=$oldest+$lastRec;
  379.  
  380. =back
  381.  
  382. =item $handle->Clear(FILENAME);
  383.  
  384. The I<Clear()> method clears the EventLog represented by $handle.
  385. If you provide a non-null B<FILENAME>, the EventLog will be backed
  386. up into B<FILENAME> before the EventLog is cleared. The method will
  387. fail if B<FILENAME> is specified and the file refered to exists. Note
  388. also that B<FILENAME> specifies a file local to the machine on which
  389. the EventLog resides and cannot be specified as a UNC name.
  390.  
  391. =item $handle->Report(HASHREF);
  392.  
  393. The I<Report()> method generates an EventLog entry. The HASHREF
  394. should contain the following keys: -
  395.  
  396. =over 4
  397.  
  398. =item Computer
  399.  
  400. The B<Computer> field specfies which computer you want the EventLog
  401. entry recorded.  If this key doesn't exist, the server name used
  402. to create the $handle is used.
  403.  
  404. =item Source
  405.  
  406. The B<Source> field specifies the source that generated the EventLog entry.
  407. If this key doesn't exist, the source name used to create the $handle is
  408. used.
  409.  
  410. =item EventType
  411.  
  412. The B<EventType> field should be one of the constants
  413.  
  414. =over 4
  415.  
  416. =item EVENTLOG_ERROR_TYPE
  417.  
  418. An Error event is being logged.
  419.  
  420. =item EVENTLOG_WARNING_TYPE
  421.  
  422. A Warning event is being logged.
  423.  
  424. =item EVENTLOG_INFORMATION_TYPE
  425.  
  426. An Information event is being logged.
  427.  
  428. =item EVENTLOG_AUDIT_SUCCESS
  429.  
  430. A Success Audit event is being logged (typically in the Security
  431. EventLog).
  432.  
  433. =item EVENTLOG_AUDIT_FAILURE
  434.  
  435. A Failure Audit event is being logged (typically in the Security
  436. EventLog).
  437.  
  438. =back
  439.  
  440. These constants are exported into the main namespace by default.
  441.  
  442. =item Category
  443.  
  444. The B<Category> field can have any value you want. It is specific to
  445. the particular Source.
  446.  
  447. =item EventID
  448.  
  449. The B<EventID> field should contain the ID of the message that this
  450. event pertains too. This assumes that you have an associated message
  451. file (indirectly referenced by the field B<Source>).
  452.  
  453. =item Data
  454.  
  455. The B<Data> field contains raw data associated with this event.
  456.  
  457. =item Strings
  458.  
  459. The B<Strings> field contains the single string that itself contains
  460. NUL terminated sub-strings. This are used with the EventID to generate
  461. the message as seen from (for example) the Event Viewer application.
  462.  
  463. =back
  464.  
  465. =back
  466.  
  467. =head1 Other Win32::EventLog functions.
  468.  
  469. The following functions are part of the Win32::EventLog package but
  470. are not callable from an EventLog object.
  471.  
  472. =over 4
  473.  
  474. =item GetMessageText(HASHREF);
  475.  
  476. The I<GetMessageText()> function assumes that HASHREF was obtained by
  477. a call to B<$handle->Read()>. It returns the formatted string that
  478. represents the fully resolved text of the EventLog message (such as
  479. would be seen in the Windows NT Event Viewer). For convenience, the
  480. key 'Message' in the supplied HASHREF is also set to the return value
  481. of this function.
  482.  
  483. If you set the variable $Win32::EventLog::GetMessageText to 1 then
  484. each call to B<$handle->Read()> will call this function automatically.
  485.  
  486. =head1 Example 1
  487.  
  488. The following example illustrates the way in which the EventLog module
  489. can be used. It opens the System EventLog and reads through it from
  490. oldest to newest records. For each record from the B<Source> EventLog
  491. it extracts the full text of the Entry and prints the EventLog message
  492. text out.
  493.  
  494.  use Win32::EventLog;
  495.  
  496.  $handle=Win32::EventLog->new("System", $ENV{ComputerName})
  497.      or die "Can't open Application EventLog\n";
  498.  $handle->GetNumber($recs)
  499.      or die "Can't get number of EventLog records\n";
  500.  $handle->GetOldest($base)
  501.      or die "Can't get number of oldest EventLog record\n";
  502.  
  503.  while ($x < $recs) {
  504.      $handle->Read(EVENTLOG_FORWARDS_READ|EVENTLOG_SEEK_READ,
  505.                    $base+$x,
  506.                    $hashRef)
  507.          or die "Can't read EventLog entry #$x\n";
  508.      if ($hashRef->{Source} eq "EventLog") {
  509.          Win32::EventLog::GetMessageText($hashRef);
  510.          print "Entry $x: $hashRef->{Message}\n";
  511.      }
  512.      $x++;
  513.  }
  514.  
  515. =head2 Example 2
  516.  
  517. To backup and clear the EventLogs on a remote machine, do the following :-
  518.  
  519.  use Win32::EventLog;
  520.  
  521.  $myServer="\\\\my-server";    # your servername here.
  522.  my($date)=join("-", ((split(/\s+/, scalar(localtime)))[0,1,2,4]));
  523.  my($dest);
  524.  
  525.  for my $eventLog ("Application", "System", "Security") {
  526.      $handle=Win32::EventLog->new($eventLog, $myServer)
  527.          or die "Can't open Application EventLog on $myServer\n";
  528.         
  529.      $dest="C:\\BackupEventLogs\\$eventLog\\$date.evt";
  530.     $handle->Backup($dest)
  531.         or warn "Could not backup and clear the $eventLog EventLog on $myServer ($^E)\n";
  532.         
  533.     $handle->Close;
  534.  }
  535.  
  536. Note that only the Clear method is required. Note also that if the file
  537. $dest exists, the function will fail.
  538.  
  539. =head1 BUGS
  540.  
  541. None currently known.
  542.  
  543. The test script for 'make test' should be re-written to use the EventLog object.
  544.  
  545. =head1 SEE ALSO
  546.  
  547. Perl(1)
  548.  
  549. =head1 AUTHOR
  550.  
  551. Original code by Jesse Dougherty for HiP Communications. Additional
  552. fixes and updates attributed to Martin Pauley 
  553. <martin.pauley@ulsterbank.ltd.uk>) and Bret Giddings (bret@essex.ac.uk).
  554.