def create_subscription(self): # https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createeventa # http://timgolden.me.uk/pywin32-docs/win32event__CreateEvent_meth.html self._event_handle = win32event.CreateEvent(None, 0, 0, self.check_id) bookmark = self.read_persistent_cache('bookmark') if bookmark: flags = win32evtlog.EvtSubscribeStartAfterBookmark else: flags = self.START_OPTIONS[self._subscription_start] # Set explicitly to None rather than a potentially empty string bookmark = None # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtcreatebookmark # http://timgolden.me.uk/pywin32-docs/win32evtlog__EvtCreateBookmark_meth.html self._bookmark_handle = win32evtlog.EvtCreateBookmark(bookmark) # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtsubscribe # http://timgolden.me.uk/pywin32-docs/win32evtlog__EvtSubscribe_meth.html self._subscription = win32evtlog.EvtSubscribe( self._path, flags, SignalEvent=self._event_handle, Query=self._query, Session=self._session, Bookmark=self._bookmark_handle if bookmark else None, ) # https://docs.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtcreaterendercontext # https://docs.microsoft.com/en-us/windows/win32/api/winevt/ne-winevt-evt_render_context_flags self._render_context_system = win32evtlog.EvtCreateRenderContext( win32evtlog.EvtRenderContextSystem) self._render_context_data = win32evtlog.EvtCreateRenderContext( win32evtlog.EvtRenderContextUser)
def log_event(self, event): render_context = win32evtlog.EvtCreateRenderContext( win32evtlog.EvtRenderContextSystem) vals = self.GetFormattedEventAsDict(render_context, event) provider = "not-specified" if "ProviderName" in vals: provider = vals["ProviderName"] if "ProviderGuid" in vals: vals["ProviderGuid"] = six.text_type(vals["ProviderGuid"]) if "ActivityId" in vals: vals["ActivityId"] = six.text_type(vals["ActivityId"]) if "RelatedActivityId" in vals: vals["RelatedActivityId"] = six.text_type( vals["RelatedActivityId"]) if "TimeCreated" in vals: time_format = "%Y-%m-%d %H:%M:%SZ" vals["TimeCreated"] = time.strftime( time_format, time.gmtime(int(vals["TimeCreated"]))) if "Keywords" in vals: if isinstance(vals["Keywords"], list): vals["Keywords"] = ",".join(vals["Keywords"]) else: vals["Keywords"] = six.text_type(vals["Keywords"]) if "UserId" in vals: user_id = six.text_type(vals["UserId"]) if user_id.startswith("PySID:"): user_id = user_id[6:] vals["UserId"] = user_id self._logger.emit_value("EventLog", provider, extra_fields=vals) self.__bookmark_lock.acquire() try: if "Channel" in vals: channel = vals["Channel"] bookmark = None if channel not in self.__bookmarks: self.__bookmarks[channel] = win32evtlog.EvtCreateBookmark( None) bookmark = self.__bookmarks[channel] win32evtlog.EvtUpdateBookmark(bookmark, event) finally: self.__bookmark_lock.release()
def log_event(self, event): render_context = win32evtlog.EvtCreateRenderContext( win32evtlog.EvtRenderContextSystem) vals = self.GetFormattedEventAsDict(render_context, event) provider = 'not-specified' if 'ProviderName' in vals: provider = vals['ProviderName'] if 'ProviderGuid' in vals: vals['ProviderGuid'] = str(vals['ProviderGuid']) if 'ActivityId' in vals: vals['ActivityId'] = str(vals['ActivityId']) if 'RelatedActivityId' in vals: vals['RelatedActivityId'] = str(vals['RelatedActivityId']) if 'TimeCreated' in vals: time_format = "%Y-%m-%d %H:%M:%SZ" vals['TimeCreated'] = time.strftime( time_format, time.gmtime(int(vals['TimeCreated']))) if 'Keywords' in vals: if isinstance(vals['Keywords'], list): vals['Keywords'] = ','.join(vals['Keywords']) else: vals['Keywords'] = str(vals['Keywords']) if 'UserId' in vals: user_id = str(vals['UserId']) if user_id.startswith("PySID:"): user_id = user_id[6:] vals['UserId'] = user_id self._logger.emit_value("EventLog", provider, extra_fields=vals) self.__bookmark_lock.acquire() try: if 'Channel' in vals: channel = vals['Channel'] bookmark = None if channel not in self.__bookmarks: self.__bookmarks[channel] = win32evtlog.EvtCreateBookmark( None) bookmark = self.__bookmarks[channel] win32evtlog.EvtUpdateBookmark(bookmark, event) finally: self.__bookmark_lock.release()
def main(): path = 'System' num_events = 5 if len(sys.argv) > 2: path = sys.argv[1] num_events = int(sys.argv[2]) elif len(sys.argv) > 1: path = sys.argv[1] query = win32evtlog.EvtQuery(path, win32evtlog.EvtQueryForwardDirection) events = win32evtlog.EvtNext(query, num_events) context = win32evtlog.EvtCreateRenderContext( win32evtlog.EvtRenderContextSystem) for i, event in enumerate(events, 1): result = win32evtlog.EvtRender(event, win32evtlog.EvtRenderEventValues, Context=context) print(('Event {}'.format(i))) level_value, level_variant = result[win32evtlog.EvtSystemLevel] if level_variant != win32evtlog.EvtVarTypeNull: if level_value == 1: print(' Level: CRITICAL') elif level_value == 2: print(' Level: ERROR') elif level_value == 3: print(' Level: WARNING') elif level_value == 4: print(' Level: INFO') elif level_value == 5: print(' Level: VERBOSE') else: print(' Level: UNKNOWN') time_created_value, time_created_variant = result[ win32evtlog.EvtSystemTimeCreated] if time_created_variant != win32evtlog.EvtVarTypeNull: print((' Timestamp: {}'.format(time_created_value.isoformat()))) computer_value, computer_variant = result[ win32evtlog.EvtSystemComputer] if computer_variant != win32evtlog.EvtVarTypeNull: print((' FQDN: {}'.format(computer_value))) provider_name_value, provider_name_variant = result[ win32evtlog.EvtSystemProviderName] if provider_name_variant != win32evtlog.EvtVarTypeNull: print((' Provider: {}'.format(provider_name_value))) try: metadata = win32evtlog.EvtOpenPublisherMetadata( provider_name_value) # pywintypes.error: (2, 'EvtOpenPublisherMetadata', 'The system cannot find the file specified.') except Exception: pass else: try: message = win32evtlog.EvtFormatMessage( metadata, event, win32evtlog.EvtFormatMessageEvent) # pywintypes.error: (15027, 'EvtFormatMessage: allocated 0, need buffer of size 0', 'The message resource is present but the message was not found in the message table.') except Exception: pass else: print((' Message: {}'.format(message)))
def main(): path = "System" num_events = 5 if len(sys.argv) > 2: path = sys.argv[1] num_events = int(sys.argv[2]) elif len(sys.argv) > 1: path = sys.argv[1] query = win32evtlog.EvtQuery(path, win32evtlog.EvtQueryForwardDirection) events = win32evtlog.EvtNext(query, num_events) context = win32evtlog.EvtCreateRenderContext( win32evtlog.EvtRenderContextSystem) for i, event in enumerate(events, 1): result = win32evtlog.EvtRender(event, win32evtlog.EvtRenderEventValues, Context=context) print("Event {}".format(i)) level_value, level_variant = result[win32evtlog.EvtSystemLevel] if level_variant != win32evtlog.EvtVarTypeNull: if level_value == 1: print(" Level: CRITICAL") elif level_value == 2: print(" Level: ERROR") elif level_value == 3: print(" Level: WARNING") elif level_value == 4: print(" Level: INFO") elif level_value == 5: print(" Level: VERBOSE") else: print(" Level: UNKNOWN") time_created_value, time_created_variant = result[ win32evtlog.EvtSystemTimeCreated] if time_created_variant != win32evtlog.EvtVarTypeNull: print(" Timestamp: {}".format(time_created_value.isoformat())) computer_value, computer_variant = result[ win32evtlog.EvtSystemComputer] if computer_variant != win32evtlog.EvtVarTypeNull: print(" FQDN: {}".format(computer_value)) provider_name_value, provider_name_variant = result[ win32evtlog.EvtSystemProviderName] if provider_name_variant != win32evtlog.EvtVarTypeNull: print(" Provider: {}".format(provider_name_value)) try: metadata = win32evtlog.EvtOpenPublisherMetadata( provider_name_value) # pywintypes.error: (2, 'EvtOpenPublisherMetadata', 'The system cannot find the file specified.') except Exception: pass else: try: message = win32evtlog.EvtFormatMessage( metadata, event, win32evtlog.EvtFormatMessageEvent) # pywintypes.error: (15027, 'EvtFormatMessage: allocated 0, need buffer of size 0', 'The message resource is present but the message was not found in the message table.') except Exception: pass else: try: print(" Message: {}".format(message)) except UnicodeEncodeError: # Obscure error when run under subprocess.Popen(), presumably due to # not knowing the correct encoding for the console. # > UnicodeEncodeError: \'charmap\' codec can\'t encode character \'\\u200e\' in position 57: character maps to <undefined>\r\n' # Can't reproduce when running manually, so it seems more a subprocess.Popen() # than ours: print(" Failed to decode:", repr(message))