Python win32evtlog.ReadEventLog() Examples
The following are 8
code examples of win32evtlog.ReadEventLog().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
win32evtlog
, or try the search function
.
Example #1
Source File: test_logging.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
def test_basic(self): logtype = 'Application' elh = win32evtlog.OpenEventLog(None, logtype) num_recs = win32evtlog.GetNumberOfEventLogRecords(elh) try: h = logging.handlers.NTEventLogHandler('test_logging') except pywintypes.error as e: if e.winerror == 5: # access denied raise unittest.SkipTest('Insufficient privileges to run test') raise r = logging.makeLogRecord({'msg': 'Test Log Message'}) h.handle(r) h.close() # Now see if the event is recorded self.assertLess(num_recs, win32evtlog.GetNumberOfEventLogRecords(elh)) flags = win32evtlog.EVENTLOG_BACKWARDS_READ | \ win32evtlog.EVENTLOG_SEQUENTIAL_READ found = False GO_BACK = 100 events = win32evtlog.ReadEventLog(elh, flags, GO_BACK) for e in events: if e.SourceName != 'test_logging': continue msg = win32evtlogutil.SafeFormatMessage(e, logtype) if msg != 'Test Log Message\r\n': continue found = True break msg = 'Record not found in event log, went back %d records' % GO_BACK self.assertTrue(found, msg=msg) # Set the locale to the platform-dependent default. I have no idea # why the test does this, but in any case we save the current locale # first and restore it at the end.
Example #2
Source File: eventLogDemo.py From ironpython2 with Apache License 2.0 | 5 votes |
def ReadLog(computer, logType="Application", dumpEachRecord = 0): # read the entire log back. h=win32evtlog.OpenEventLog(computer, logType) numRecords = win32evtlog.GetNumberOfEventLogRecords(h) # print "There are %d records" % numRecords num=0 while 1: objects = win32evtlog.ReadEventLog(h, win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0) if not objects: break for object in objects: # get it for testing purposes, but dont print it. msg = win32evtlogutil.SafeFormatMessage(object, logType) if object.Sid is not None: try: domain, user, typ = win32security.LookupAccountSid(computer, object.Sid) sidDesc = "%s/%s" % (domain, user) except win32security.error: sidDesc = str(object.Sid) user_desc = "Event associated with user %s" % (sidDesc,) else: user_desc = None if dumpEachRecord: print "Event record from %r generated at %s" % (object.SourceName, object.TimeGenerated.Format()) if user_desc: print user_desc try: print msg except UnicodeError: print "(unicode error printing message: repr() follows...)" print repr(msg) num = num + len(objects) if numRecords == num: print "Successfully read all", numRecords, "records" else: print "Couldn't get all records - reported %d, but found %d" % (numRecords, num) print "(Note that some other app may have written records while we were running!)" win32evtlog.CloseEventLog(h)
Example #3
Source File: win32evtlogutil.py From ironpython2 with Apache License 2.0 | 5 votes |
def FormatMessage( eventLogRecord, logType="Application" ): """Given a tuple from ReadEventLog, and optionally where the event record came from, load the message, and process message inserts. Note that this function may raise win32api.error. See also the function SafeFormatMessage which will return None if the message can not be processed. """ # From the event log source name, we know the name of the registry # key to look under for the name of the message DLL that contains # the messages we need to extract with FormatMessage. So first get # the event log source name... keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (logType, eventLogRecord.SourceName) # Now open this key and get the EventMessageFile value, which is # the name of the message DLL. handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName) try: dllNames = win32api.RegQueryValueEx(handle, "EventMessageFile")[0].split(";") # Win2k etc appear to allow multiple DLL names data = None for dllName in dllNames: try: # Expand environment variable strings in the message DLL path name, # in case any are there. dllName = win32api.ExpandEnvironmentStrings(dllName) dllHandle = win32api.LoadLibraryEx(dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE) try: data = win32api.FormatMessageW(win32con.FORMAT_MESSAGE_FROM_HMODULE, dllHandle, eventLogRecord.EventID, langid, eventLogRecord.StringInserts) finally: win32api.FreeLibrary(dllHandle) except win32api.error: pass # Not in this DLL - try the next if data is not None: break finally: win32api.RegCloseKey(handle) return data or u'' # Don't want "None" ever being returned.
Example #4
Source File: win32evtlogutil.py From ironpython2 with Apache License 2.0 | 5 votes |
def FeedEventLogRecords(feeder, machineName = None, logName = "Application", readFlags = None): if readFlags is None: readFlags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ h=win32evtlog.OpenEventLog(machineName, logName) try: while 1: objects = win32evtlog.ReadEventLog(h, readFlags, 0) if not objects: break map(lambda item, feeder = feeder: feeder(*(item,)), objects) finally: win32evtlog.CloseEventLog(h)
Example #5
Source File: test_logging.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_basic(self): logtype = 'Application' elh = win32evtlog.OpenEventLog(None, logtype) num_recs = win32evtlog.GetNumberOfEventLogRecords(elh) try: h = logging.handlers.NTEventLogHandler('test_logging') except pywintypes.error as e: if e.winerror == 5: # access denied raise unittest.SkipTest('Insufficient privileges to run test') raise r = logging.makeLogRecord({'msg': 'Test Log Message'}) h.handle(r) h.close() # Now see if the event is recorded self.assertLess(num_recs, win32evtlog.GetNumberOfEventLogRecords(elh)) flags = win32evtlog.EVENTLOG_BACKWARDS_READ | \ win32evtlog.EVENTLOG_SEQUENTIAL_READ found = False GO_BACK = 100 events = win32evtlog.ReadEventLog(elh, flags, GO_BACK) for e in events: if e.SourceName != 'test_logging': continue msg = win32evtlogutil.SafeFormatMessage(e, logtype) if msg != 'Test Log Message\r\n': continue found = True break msg = 'Record not found in event log, went back %d records' % GO_BACK self.assertTrue(found, msg=msg) # Set the locale to the platform-dependent default. I have no idea # why the test does this, but in any case we save the current locale # first and restore it at the end.
Example #6
Source File: logs.py From Fastir_Collector with GNU General Public License v3.0 | 5 votes |
def _list_evt_xp(self, server, logtype): """Retrieves the contents of the event log for Windows XP""" self.logger.info('Exporting logs for : ' + logtype) hand = win32evtlog.OpenEventLog(server, logtype) flags = win32evtlog.EVENTLOG_FORWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ total = win32evtlog.GetNumberOfEventLogRecords(hand) sum_evt = 0 while True: events = win32evtlog.ReadEventLog(hand, flags, 0) sum_evt += len(events) if events: for event in events: data = event.StringInserts date = datetime.datetime(event.TimeGenerated.year, event.TimeGenerated.month, event.TimeGenerated.day, event.TimeGenerated.hour, event.TimeGenerated.minute, event.TimeGenerated.second).strftime( '%d/%m/%Y %H:%M:%S') # print date + ' : ' + log_type + ' -> ' + log_data if data: yield unicode(event.EventCategory), unicode(event.SourceName), unicode(event.EventID), unicode( event.EventType), date, list(data) else: yield unicode(event.EventCategory), unicode(event.SourceName), unicode(event.EventID), unicode( event.EventType), date, [] if sum_evt >= total: break
Example #7
Source File: test_logging.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_basic(self): logtype = 'Application' elh = win32evtlog.OpenEventLog(None, logtype) num_recs = win32evtlog.GetNumberOfEventLogRecords(elh) try: h = logging.handlers.NTEventLogHandler('test_logging') except pywintypes.error as e: if e.winerror == 5: # access denied raise unittest.SkipTest('Insufficient privileges to run test') raise r = logging.makeLogRecord({'msg': 'Test Log Message'}) h.handle(r) h.close() # Now see if the event is recorded self.assertLess(num_recs, win32evtlog.GetNumberOfEventLogRecords(elh)) flags = win32evtlog.EVENTLOG_BACKWARDS_READ | \ win32evtlog.EVENTLOG_SEQUENTIAL_READ found = False GO_BACK = 100 events = win32evtlog.ReadEventLog(elh, flags, GO_BACK) for e in events: if e.SourceName != 'test_logging': continue msg = win32evtlogutil.SafeFormatMessage(e, logtype) if msg != 'Test Log Message\r\n': continue found = True break msg = 'Record not found in event log, went back %d records' % GO_BACK self.assertTrue(found, msg=msg) # Set the locale to the platform-dependent default. I have no idea # why the test does this, but in any case we save the current locale # first and restore it at the end.
Example #8
Source File: windows_event_log_monitor.py From scalyr-agent-2 with Apache License 2.0 | 4 votes |
def __read_from_event_log(self, source, event_types): event_log = win32evtlog.OpenEventLog(self._server, source) if not event_log: self._logger.error("Unknown error opening event log for '%s'" % source) return # we read events in reverse from the end of the log to avoid problems when # seeking directly to a record in a large log file flags = ( win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ ) offset = -1 # use the checkpoint if it exists if source in self._checkpoints: offset = self._checkpoints[source] # a list of events that we haven't yet seen event_list = [] try: events = True while events: events = win32evtlog.ReadEventLog(event_log, flags, offset) for event in events: # special case for when there was no offset, in which case # the first event will be the latest event so use that for the # new offset if offset == -1: self._checkpoints[source] = event.RecordNumber events = False break # if we encounter our last seen record, then we are done elif ( offset == event.RecordNumber or len(event_list) >= self._maximum_records ): events = False break else: # add the event to our list of interested events # if it is one we are interested in if event.EventType in event_types: event_list.append(event) except Exception as error: self._logger.error( "Error reading from event log: %s", six.text_type(error), limit_once_per_x_secs=self._error_repeat_interval, limit_key="EventLogError", ) # now print out records in reverse order (which will put them in correct chronological order # because we initially read them in reverse) for event in reversed(event_list): self.__log_event(source, event) self._checkpoints[source] = event.RecordNumber