def get_power_of_records(self) -> Iterable[dict]: server = "localhost" for logtype in ["System", "Application", "Security"]: hand = win32evtlog.OpenEventLog(server, logtype) flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ events = win32evtlog.ReadEventLog(hand, flags, 0) try: events = 1 while events: events = win32evtlog.ReadEventLog(hand, flags, 0) for ev_obj in events: infoTemp = {} if winerror.HRESULT_CODE(ev_obj.EventID) == 6005: infoTemp["time"] = ev_obj.TimeGenerated.Format() infoTemp["event"] = "power on" infoTemp["user"] = str(ev_obj.ComputerName) elif winerror.HRESULT_CODE(ev_obj.EventID) == 6006: infoTemp["time"] = ev_obj.TimeGenerated.Format() infoTemp["event"] = "power off" infoTemp["user"] = str(ev_obj.ComputerName) elif winerror.HRESULT_CODE(ev_obj.EventID) == 6008: infoTemp["time"] = ev_obj.TimeGenerated.Format() infoTemp["event"] = "power off" infoTemp["user"] = str(ev_obj.ComputerName) else: continue yield infoTemp except: print(traceback.print_exc(sys.exc_info()))
def getEventLogs(self, server, logtype, logPath): """ Get the event logs from the specified machine according to the logtype (Example: Application) and save it to the appropriately named log file """ print("Logging %s events" % logtype) log = codecs.open(logPath, encoding='utf-8', mode='w') line_break = '-' * 80 log.write("\n%s Log of %s Events\n" % (server, logtype)) log.write("Created: %s\n\n" % time.ctime()) log.write("\n" + line_break + "\n") hand = win32evtlog.OpenEventLog(server, logtype) total = win32evtlog.GetNumberOfEventLogRecords(hand) print("Total events in %s = %s" % (logtype, total)) flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ events = win32evtlog.ReadEventLog(hand, flags, 0) evt_dict = { win32con.EVENTLOG_AUDIT_FAILURE: 'EVENTLOG_AUDIT_FAILURE', win32con.EVENTLOG_AUDIT_SUCCESS: 'EVENTLOG_AUDIT_SUCCESS', win32con.EVENTLOG_INFORMATION_TYPE: 'EVENTLOG_INFORMATION_TYPE', win32con.EVENTLOG_WARNING_TYPE: 'EVENTLOG_WARNING_TYPE', win32con.EVENTLOG_ERROR_TYPE: 'EVENTLOG_ERROR_TYPE' } try: events = 1 while events: events = win32evtlog.ReadEventLog(hand, flags, 0) for ev_obj in events: the_time = ev_obj.TimeGenerated.Format( ) #'12/23/99 15:54:09' evt_id = str(winerror.HRESULT_CODE(ev_obj.EventID)) computer = str(ev_obj.ComputerName) cat = ev_obj.EventCategory record = ev_obj.RecordNumber msg = win32evtlogutil.SafeFormatMessage(ev_obj, logtype) source = str(ev_obj.SourceName) if not ev_obj.EventType in evt_dict.keys(): evt_type = "unknown" else: evt_type = str(evt_dict[ev_obj.EventType]) log.write("Event Date/Time: %s\n" % the_time) log.write("Event ID / Type: %s / %s\n" % (evt_id, evt_type)) log.write("Currently Active User(s): %s\n" % self.currentUsers) log.write("Record #%s\n" % record) log.write("Source: %s\n\n" % source) log.write(msg) log.write("\n\n") log.write(line_break) log.write("\n\n") except: print(traceback.print_exc(sys.exc_info())) print("Log creation finished. Location of log is %s" % logPath)
def get_olprops_from_mapi(self, entryid=None): """This reads the current contact's entire property list from MAPI and returns an array of property tuples""" oli = self.get_olitem() # prop_list = oli.GetPropList(mapi.MAPI_UNICODE) # hr, props = oli.GetProps(prop_list, 0) # hr, props = oli.GetProps(self.get_folder().get_def_cols(), 0) # The idea here is to get the full property list, and then filter down # to the ones we are really interested in. It was getting a bit # confusing, as the available property list was getting filtered # somewhere upstream, and we were not even seeing basic stuff like # PR_BODY and PR_GIVEN_NAME. The following approach works for now, # i.e. just set the properties we are keen on. hr, props = oli.GetProps(self.get_sync_fields(), 0) # hr, props = oli.GetProps(None, 0) if (winerror.FAILED(hr)): logging.error( 'get_olprops_from_mapi: Unable to GetProps. Code: %x', winerror.HRESULT_CODE(hr)) logging.error('Formatted error: %s', win32api.FormatMessage(hr)) return props
def create_contact(self, name, email=None, org=None): """Save the current contact to Outlook, and returns the entryid of the entry.""" logging.info('Saving to Outlook: %-32s ....', name) msg = self.def_cf.CreateMessage(None, 0) if not msg: return None self.props_list = [(mapitags.PR_MESSAGE_CLASS, "IPM.Contact")] self.props_list.append((mapitags.PR_DISPLAY_NAME, name)) fileas_prop_tag = self.get_file_as_prop_tag() self.props_list.append((fileas_prop_tag, name)) self.props_list.append((mapitags.PR_COMPANY_NAME, org)) self.props_list.append((mapitags.PR_BODY, email)) hr, res = msg.SetProps(self.props_list) if (winerror.FAILED(hr)): logging.critical( 'push_to_outlook(): unable to SetProps (code: %x)', winerror.HRESULT_CODE(hr)) return None msg.SaveChanges(mapi.KEEP_OPEN_READWRITE)
def event_logs(server="localhost", source="System"): # type: (str, str) -> Iterator[dict] """ EventType: severity level EVENTLOG_ERROR_TYPE 0x0001 EVENTLOG_WARNING_TYPE 0x0002 EVENTLOG_INFORMATION_TYPE 0x0004 EVENTLOG_AUDIT_SUCCESS 0x0008 EVENTLOG_AUDIT_FAILURE 0x0010 EventID: same for same class of messages, stringinserts are provides to template belonging to eventid """ fields = { "Reserved", "RecordNumber", "TimeGenerated", "TimeWritten", "EventID", "EventType", "EventCategory", "ReservedFlags", "ClosingRecordNumber", "SourceName", "StringInserts", "Sid", "Data", "ComputerName" } fields = { "Reserved", "RecordNumber", "TimeGenerated", "TimeWritten", "EventID", "EventType", "EventCategory", "ReservedFlags", "ClosingRecordNumber", "SourceName", "StringInserts", "ComputerName" } # missing: "Sid", "Data" handle = win32evtlog.OpenEventLog(server, source) flags = win32evtlog.EVENTLOG_SEQUENTIAL_READ | win32evtlog.EVENTLOG_FORWARDS_READ logger.debug("Preparing to read {} events".format( win32evtlog.GetNumberOfEventLogRecords(handle))) try: while True: events = win32evtlog.ReadEventLog(handle, flags, 0) if events: for event in events: ret = {f: getattr(event, f) for f in fields} # does that work for different time zones? ret["TimeGenerated"] = datetime.fromtimestamp( event.TimeGenerated.timestamp()) ret["TimeWritten"] = datetime.fromtimestamp( event.TimeWritten.timestamp()) if ret["StringInserts"]: ret["StringInserts"] = ", ".join( ret["StringInserts"]).replace("\r\n", "\n") if not ret["StringInserts"]: ret["StringInserts"] = None ret["EventID"] = winerror.HRESULT_CODE(ret["EventID"]) #print(ret) yield ret else: break finally: win32evtlog.CloseEventLog(handle)
def analyze_one_log(event_log: str) -> None: """ Main analysis. Go thru events in one event log, compile statistics. Args: event_log (string): name of Windows Event Log to read. Returns: none. Raises: none. """ # Summary of one event. keys = [ 'EventID', 'Computer', 'Category', 'Source Name', 'Event Type', 'User Name', 'Log Name' ] event_summary = dict.fromkeys(keys, "") # Where we compile event statistics. event_stats = {} # Handle to a Windows Event Log. handle = win32evtlog.OpenEventLog('localhost', event_log) # Flags for reading the Event Log. flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ # num_events = win32evtlog.GetNumberOfEventLogRecords(handle) try: events = 1 while events: events = win32evtlog.ReadEventLog(handle, flags, 0) for event in events: # Unpack each event. event_summary['EventID'] = winerror.HRESULT_CODE(event.EventID) event_summary['Computer'] = event.ComputerName event_summary['Category'] = event.EventCategory event_summary['Source Name'] = event.SourceName event_summary['Event Type'] = type_name(event.EventType) event_summary['User Name'] = get_user_name(event.Sid) event_summary['Log Name'] = event_log # record_num = event.RecordNumber # string_inserts = event.StringInserts # message = win32evtlogutil.SafeFormatMessage(event, event_log) # Tally statistics. if frozendict(event_summary) in event_stats.keys(): event_stats[frozendict(event_summary)] += 1 else: event_stats[frozendict(event_summary)] = 1 except Exception: print(traceback.print_exc(sys.exc_info())) # Print event statistics. for event_summary, count in sorted(event_stats.items(), reverse=True, key=lambda item: item[1]): print("\n## {} occurrences of this event:".format(count)) for key, value in event_summary.items(): print(str(key) + ": " + str(value))
def getEventLogs(server, logtype, logPath): log = codecs.open(logPath, encoding='utf-8', mode='w') begin_sec = time.time() begin_time = time.strftime('%H:%M:%S ', time.localtime(begin_sec)) hand = win32evtlog.OpenEventLog(server, logtype) flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ events = win32evtlog.ReadEventLog(hand, flags, 0) evt_dict = { win32con.EVENTLOG_AUDIT_FAILURE: 'EVENTLOG_AUDIT_FAILURE', win32con.EVENTLOG_AUDIT_SUCCESS: 'EVENTLOG_AUDIT_SUCCESS', win32con.EVENTLOG_INFORMATION_TYPE: 'EVENTLOG_INFORMATION_TYPE', win32con.EVENTLOG_WARNING_TYPE: 'EVENTLOG_WARNING_TYPE', win32con.EVENTLOG_ERROR_TYPE: 'EVENTLOG_ERROR_TYPE' } try: events = 1 while events: events = win32evtlog.ReadEventLog(hand, flags, 0) for ev_obj in events: the_time = ev_obj.TimeGenerated.Format() # '12/23/99 15:54:09' seconds = date2sec(the_time) if seconds < begin_sec - 15: break evt_id = str(winerror.HRESULT_CODE(ev_obj.EventID)) event_list = [ event for event in events if event.EventID == "27035" ] if event_list: print 'Event Category:', event_list[0].EventCategory computer = str(ev_obj.ComputerName) cat = ev_obj.EventCategory record = ev_obj.RecordNumber msg = win32evtlogutil.SafeFormatMessage(ev_obj, logtype) source = str(ev_obj.SourceName) if not ev_obj.EventType in evt_dict.keys(): evt_type = "unknown" else: evt_type = str(evt_dict[ev_obj.EventType]) # logging.info("Event Date/Time: %s\n" % the_time) # logging.info("Event ID / Type: %s / %s\n" % (evt_id, evt_type)) if evt_id in ['4625']: # An account failed to log on print "XXXXXXXXXXXXXXXXxxxxxxxxx--------FAILED LOGIN!!!" begin_sec = time.time() the_time = ev_obj.TimeGenerated.Format() seconds = date2sec(the_time) os.startfile(os.getcwd() + '\\dist\\capture_me.exe') logging.info("Record #%s" % record) logging.info("Source: %s" % source) logging.info(msg) logging.info('-' * 80) except: message = traceback.print_exc(sys.exc_info()) logging.error(message)
def get_ipm_subtree_eid (self): msgstore = self.get_obj() hr, ps = msgstore.GetProps((mapitags.PR_IPM_SUBTREE_ENTRYID)) if winerror.FAILED(hr): logging.error('Could not get subtree entryid for store: %s. ' 'Error: 0x%x', self.get_name(), winerror.HRESULT_CODE(hr)) return None tag, eid = ps[0] return eid
def FormatEv(ev_obj, logtype): computer = str(ev_obj.ComputerName) # cat=str(ev_obj.EventCategory) level = str(ev_obj.EventType) record = str(ev_obj.RecordNumber) evt_id = str(winerror.HRESULT_CODE(ev_obj.EventID)) evt_type = evt_dict.get(ev_obj.EventType, 'UNK') msg = win32evtlogutil.SafeFormatMessage(ev_obj, logtype) epoch = int(ev_obj.TimeGenerated) msg = u'=== eventid=%d eventtype=%s epoch=%d time="%s" ===\r\n%s' % ( ev_obj.EventID, evt_type, epoch, time.ctime(epoch), msg) #print ev_obj.EventID, evt_type, int(ev_obj.TimeGenerated), level, msg.encode('UTF-8') return msg
def _clear_tag(self, tags, dryrun=False): """Clear any property whose property tag is the provided array.""" logging.info('Querying MAPI for all data needed to clear flag') ctable = self.get_contents() cols = tuple([mt.PR_ENTRYID, mt.PR_DISPLAY_NAME]) + tuple(tags) ctable.SetColumns(cols, 0) logging.info('Data obtained from MAPI. Clearing one at a time') cnt = set() errs = set() i = 0 store = self.get_msgstore().get_obj() hr = ctable.SeekRow(mapi.BOOKMARK_BEGINNING, 0) while True: rows = ctable.QueryRows(1, 0) # if this is the last row then stop if len(rows) != 1: break (entryid_tag, entryid), (name_tag, name) = rows[0][:2] i += 1 for j in range(2, len(rows[0])): (gid_tag, gid) = rows[0][j] if mt.PROP_TYPE(gid_tag) != mt.PT_ERROR: if not dryrun: entry = store.OpenEntry(entryid, None, mapi.MAPI_BEST_ACCESS) hr, ps = entry.DeleteProps([gid_tag]) if winerror.FAILED(hr): logging.debug( 'Could not delete sync tag for: %s ' '(%s), due to: %s', name, base64.b64encode(entryid), winerror.HRESULT_CODE(hr)) errs.add(entryid) else: entry.SaveChanges(0) cnt.add(entryid) logging.info('Entries cleared: %d. Errors: %d; i: %d', len(cnt), len(errs), i) ctable.SetColumns(self.get_def_cols(), 0) return (len(errs) == 0)
def SafeFormatMessage(eventLogRecord, logType=None): """As for FormatMessage, except returns an error message if the message can not be processed. """ if logType is None: logType = "Application" try: return FormatMessage(eventLogRecord, logType) except win32api.error: if eventLogRecord.StringInserts is None: desc = "" else: desc = u", ".join(eventLogRecord.StringInserts) return u"<The description for Event ID ( %d ) in Source ( %r ) could not be found. It contains the following insertion string(s):%r.>" % ( winerror.HRESULT_CODE( eventLogRecord.EventID), eventLogRecord.SourceName, desc)
def CreateISAPIFilter(filterParams, options): server = FindWebServer(options, filterParams.Server) _CallHook(filterParams, "PreInstall", options) try: filters = GetObject(server + "/Filters") except pythoncom.com_error, exc: # Brand new sites don't have the '/Filters' collection - create it. # Any errors other than 'not found' we shouldn't ignore. if winerror.HRESULT_FACILITY(exc.hresult) != winerror.FACILITY_WIN32 or \ winerror.HRESULT_CODE(exc.hresult) != winerror.ERROR_PATH_NOT_FOUND: raise server_ob = GetObject(server) filters = server_ob.Create(_IIS_FILTERS, "Filters") filters.FilterLoadOrder = "" filters.SetInfo()
def enumerate_ipm_folders (self): """Walk through all the folders in the IPM subtree of the message store and print one line per folder with some critical information. For more information on what a IPM Subtree is, look here: http://msdn.microsoft.com/en-us/library/cc815825.aspx """ msgstore = self.get_obj() hr, ps = msgstore.GetProps((mapitags.PR_IPM_SUBTREE_ENTRYID)) if winerror.FAILED(hr): logging.error('Could not get subtree entryid for store: %s. ' 'Error: 0x%x', self.get_name(), winerror.HRESULT_CODE(hr)) return tag, ipm_eid = ps[0] folder = msgstore.OpenEntry(ipm_eid, None, MOD_FLAG) self.enumerate_all_folders(ipm_eid)
def main(computer='.', logtype='System', interval=480): flags = win32evtlog.EVENTLOG_BACKWARDS_READ|\ win32evtlog.EVENTLOG_SEQUENTIAL_READ evt_dict = { win32con.EVENTLOG_AUDIT_FAILURE: '审核失败事件', win32con.EVENTLOG_AUDIT_SUCCESS: '审核成功事件', win32con.EVENTLOG_INFORMATION_TYPE: '通知事件', win32con.EVENTLOG_WARNING_TYPE: '警告事件', win32con.EVENTLOG_ERROR_TYPE: '错误事件' } begin_sec = time.time() begin_time = time.strftime('%H:%M:%S', time.localtime(begin_sec)) try: hand = win32evtlog.OpenEventLog(computer, logtype) #打开日志 except: print('无法打开"{0}"服务器上的"{1}"日志'.format(computer, logtype)) return print( logtype, ' events found in the last {0} hours before {1}'.format( interval / 60 / 60, begin_time)) events = 1 while events: events = win32evtlog.ReadEventLog(hand, flags, 0) for ev_obj in events: try: the_time = ev_obj.TimeGenerated.Format('%D %H:%M:%S') seconds = date2sec(the_time) if seconds < begin_sec - interval: #只查看指定时间段内的日志 break computer = ev_obj.ComputerName cat = str(ev_obj.EventCategory) src = str(ev_obj.SourceName) record = str(ev_obj.RecordNumber) evt_id = str(winerror.HRESULT_CODE(ev_obj.EventID)) evt_type = evt_dict[ev_obj.EventType] msg = win32evtlogutil.SafeFormatMessage(ev_obj, logtype) print(':'.join((the_time, computer, src, cat, record, evt_id, evt_type, msg))) print('=' * 20) if seconds < begin_sec - interval: break except: pass win32evtlog.CloseEventLog(hand)
def get_system_logs_records(self) -> Iterable[dict]: server = "localhost" for logtype in ["System", "Application", "Security"]: hand = win32evtlog.OpenEventLog(server, logtype) flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ events = win32evtlog.ReadEventLog(hand, flags, 0) evt_dict = { win32con.EVENTLOG_AUDIT_FAILURE: 'Unknown', win32con.EVENTLOG_AUDIT_SUCCESS: 'Unknown', win32con.EVENTLOG_INFORMATION_TYPE: 'info', win32con.EVENTLOG_WARNING_TYPE: 'waring', win32con.EVENTLOG_ERROR_TYPE: 'error' } events = 1 while events: events = win32evtlog.ReadEventLog(hand, flags, 0) for ev_obj in events: infoTemp = {} if not ev_obj.EventType in evt_dict.keys(): evt_type = "unknown" else: evt_type = str(evt_dict[ev_obj.EventType]) infoTemp["log_type"] = logtype infoTemp["time"] = ev_obj.TimeGenerated.Format() infoTemp["event"] = str( winerror.HRESULT_CODE(ev_obj.EventID)) infoTemp["log_source"] = str(ev_obj.SourceName) try: infoTemp["description"] = ",".join( ev_obj.StringInserts[:1]) except: infoTemp["description"] = str( ev_obj.StringInserts)[1:-1] infoTemp["computer_name"] = str(ev_obj.ComputerName) infoTemp["log_kind"] = str(evt_type) yield infoTemp
def readLogs(self, log): for ev_obj in self.log_holder[log]: temp_dict = {} try: temp_dict['Source'] = str(ev_obj.SourceName).strip() except: pass try: temp_dict['Time'] = ev_obj.TimeGenerated.Format() except: pass try: temp_dict['Event ID'] = str( winerror.HRESULT_CODE(ev_obj.EventID)).strip() except: pass try: temp_dict['Computer Name'] = str(ev_obj.ComputerName).strip() except: pass try: temp_dict['Category'] = str(ev_obj.EventCategory).strip() except: pass try: temp_dict['Record Number'] = str(ev_obj.RecordNumber).strip() except: pass try: temp_dict['Message'] = str( win32evtlogutil.SafeFormatMessage(ev_obj, log)).strip() except: pass try: temp_dict['Provider Name'] = str(ev_obj.Provider).strip() except: pass try: temp_dict['Level'] = str(ev_obj.Level).strip() except: pass self.log[log].append(temp_dict)
def save(self): """Saves the current (new) contact to Outlook so it is persistent. Returns the itemid for the saved entry. Returns None in case of an error""" ## FIXME: This only takes care of new insertions. In-place updates are ## not taken care of by this. As of this time (May 2012) this method ## is only invoked for new contact creations. Updates are handld ## differently - see folder_ol:batch_update(), so this is not a bug, ## just that it would be good to have a single method deal with both ## cases. fobj = self.get_folder().get_fobj() msg = fobj.CreateMessage(None, 0) if not msg: return None olprops = self.get_olprops() hr, res = msg.SetProps(olprops) if (winerror.FAILED(hr)): logging.critical( 'push_to_outlook(): unable to SetProps (code: %x)', winerror.HRESULT_CODE(hr)) return None msg.SaveChanges(mapi.KEEP_OPEN_READWRITE) # Now that we have successfully saved the record, let's fetch the # entryid and return it to the caller. hr, props = msg.GetProps([mt.PR_ENTRYID], mapi.MAPI_UNICODE) (tag, val) = props[0] if mt.PROP_TYPE(tag) == mt.PT_ERROR: logging.error('save: EntryID could not be found. Weird') return None else: logging.debug('Successfully Wrote contact to Outlook : %-32s', self.get_name()) return self.set_entryid(val)
def CreateISAPIFilter(filterParams, options): server = FindWebServer(options, filterParams.Server) _CallHook(filterParams, "PreInstall", options) try: filters = GetObject(server + "/Filters") except pythoncom.com_error as exc: # Brand new sites don't have the '/Filters' collection - create it. # Any errors other than 'not found' we shouldn't ignore. if ( winerror.HRESULT_FACILITY(exc.hresult) != winerror.FACILITY_WIN32 or winerror.HRESULT_CODE(exc.hresult) != winerror.ERROR_PATH_NOT_FOUND ): raise server_ob = GetObject(server) filters = server_ob.Create(_IIS_FILTERS, "Filters") filters.FilterLoadOrder = "" filters.SetInfo() # As for VirtualDir, delete an existing one. assert filterParams.Name.strip("/"), "mustn't delete the root!" try: filters.Delete(_IIS_FILTER, filterParams.Name) log(2, "Deleted old filter '%s'" % (filterParams.Name,)) except pythoncom.com_error: pass newFilter = filters.Create(_IIS_FILTER, filterParams.Name) log(2, "Created new ISAPI filter...") assert os.path.isfile(filterParams.Path) newFilter.FilterPath = filterParams.Path newFilter.FilterDescription = filterParams.Description newFilter.SetInfo() load_order = [b.strip() for b in filters.FilterLoadOrder.split(",") if b] if filterParams.Name not in load_order: load_order.append(filterParams.Name) filters.FilterLoadOrder = ",".join(load_order) filters.SetInfo() _CallHook(filterParams, "PostInstall", options, newFilter) log(1, "Configured Filter: %s" % (filterParams.Name,)) return newFilter
def make_event_dict(event): ''' Will make a PyEventLogRecord into a dict. event PyEventLogRecord return dict ''' event_dict = {} for event_part in EVENT_PARTS: # get object value and add it to the event dict event_dict[event_part] = getattr(event, event_part[0].upper() + event_part[1:], None) # format items event_dict['eventID'] = winerror.HRESULT_CODE(event_dict['eventID']) if event_dict['sid'] is not None: event_dict['sid'] = event_dict['sid'].GetSidIdentifierAuthority() event_dict['timeGenerated'] = _get_raw_time(event_dict['timeGenerated']) event_dict['timeWritten'] = _get_raw_time(event_dict['timeWritten']) return _change_str_to_bytes(event_dict)
nf = folder.CreateFolder(mapi.FOLDER_GENERIC, fname, 'Comment', None, 0) folder.SaveChanges(0) except Exception, e: logging.error('Failed to create new folder %s. CreateFolder ' 'returned error code: %s', fname, str(e)) return None hr, ps = nf.SetProps([(mapitags.PR_CONTAINER_CLASS, cclass)]) if winerror.FAILED(hr): logging.error('Failed to Set Container class for newly created ' 'folder %s. Hm. tough luck... Delete the sucker ' 'manually from Outlook. Sorry for the bother. ' 'Error Code retruned by SetProps: 0x%x',fname, winerror.HRESULT_CODE(hr)) return None hr, ps = nf.GetProps((mapitags.PR_ENTRYID)) if winerror.FAILED(hr): logging.error('Failed to get Entry_ID for newly created ' 'folder %s. Hm. tough luck... Delete the sucker ' 'manually from Outlook. Sorry for the bother. ' 'Error Code retruned by SetProps: 0x%x',fname, winerror.HRESULT_CODE(hr)) return None tag, val = ps[0] val = base64.b64encode(val) logging.info('Successfully created group. ID: %s', val) return val
def getEventLogs(server,logtype,logpath): print('正在获取'+logtype+'日志') log=codecs.open(logpath,encoding='utf-8',mode='w') #读取本机的系统日志 hand=win32evtlog.OpenEventLog(server,logtype) #读取系统日志总行数 total=win32evtlog.GetNumberOfEventLogRecords(hand) #按序读取 flags=win32evtlog.EVENTLOG_FORWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ ##错误级别字典 evt_dict = {win32con.EVENTLOG_AUDIT_FAILURE: 'EVENTLOG_AUDIT_FAILURE', win32con.EVENTLOG_AUDIT_SUCCESS: 'EVENTLOG_AUDIT_SUCCESS', win32con.EVENTLOG_INFORMATION_TYPE: 'EVENTLOG_INFORMATION_TYPE', win32con.EVENTLOG_WARNING_TYPE: 'EVENTLOG_WARNING_TYPE', win32con.EVENTLOG_ERROR_TYPE: 'EVENTLOG_ERROR_TYPE'} try: events=1 j=2 WaitTime=datetime.datetime.now() WaitTime=(datetime.datetime.now()+datetime.timedelta(minutes=-1)).strftime("%Y%m%d%H%M%S") while events: events=win32evtlog.ReadEventLog(hand,flags,0) for ev_obj in events: the_time=ev_obj.TimeGenerated.Format() the_time=trans_format(the_time,'%a %b %d %H:%M:%S %Y','%Y%m%d%H%M%S') if the_time<WaitTime: continue else: evt_id=winerror.HRESULT_CODE(ev_obj.EventID) computer=ev_obj.ComputerName cat=ev_obj.EventCategory record=ev_obj.RecordNumber msg=win32evtlogutil.SafeFormatMessage(ev_obj,logtype) source=str(ev_obj.SourceName) if not ev_obj.EventType in evt_dict.keys(): evt_type="unknow" else: evt_type=evt_dict[ev_obj.EventType] log.write("Event Date/Time: %s\n" %the_time) log.write("EventID /Type: %s / %s\n" %(evt_id,evt_type)) log.write("Record #%s\n" %record) log.write("Source: %s\n\n" %source) log.write(msg) log.write('__________________________________________________') log.write('\n\n') AccountName=re.search('帐户名:\t\t.+',msg) if AccountName==None: continue else: AccountName=AccountName.group(0) AccountName=AccountName[6:] DateType=re.search('对象类型:\t\t.+',msg) #\s也可以匹配上 if DateType==None: continue else: DateType=DateType.group(0) DateType=DateType[7:] DateType=DateType[0:-1] if DateType=='File': Result=re.search("访问:\t\t.+",msg) if Result==None: continue else: Result=Result.group(0) Result=Result[7:] Result=Result[0:-1] if Result=='1537': print('删除') DoSomething=re.search('对象名:\t\t.+',msg) DoSomething=DoSomething.group(0) ws.cell(row=j,column=1).value=the_time ws.cell(row=j,column=2).value=AccountName ws.cell(row=j,column=3).value=DoSomething ws.cell(row=j,column=4).value='删除了该文件' j=j+1 elif Result=='4416': print('读取') DoSomething=re.search('对象名:\t\t.+',msg) DoSomething=DoSomething.group(0) ws.cell(row=j,column=1).value=the_time ws.cell(row=j,column=2).value=AccountName ws.cell(row=j,column=3).value=DoSomething ws.cell(row=j,column=4).value='读取该文件' j=j+1 elif Result=='4417': print('写入') DoSomething=re.search('对象名:\t\t.+',msg) DoSomething=DoSomething.group(0) ws.cell(row=j,column=1).value=the_time ws.cell(row=j,column=2).value=AccountName ws.cell(row=j,column=3).value=DoSomething ws.cell(row=j,column=4).value='写入了文件' j=j+1 else: continue #print('WIRTEDATA OR WIRTELIST') #Dir=re.search("对象名:\t\t.+",msg) except: print(traceback.print_exc(sys.exc_info()))
ev_obj.SourceName): all_events[ev_obj.EventType][str( ev_obj.SourceName)] = { 'data': [], 'count': 0 } if day.days <= 7: #print day.days all_events[ev_obj.EventType][str( ev_obj.SourceName )]['data'].append({ 'SourceName': str(ev_obj.SourceName), 'event_id': str(winerror.HRESULT_CODE(ev_obj.EventID)), # 'time': ev_obj.TimeGenerated.Format( ), #'12/23/99 15:54:09' 'hostname': str(ev_obj.ComputerName), #'record' : str(ev_obj.RecordNumber), # #'Eventcategory' : str(ev_obj.EventCategory), #'EventType': ev_obj.EventType, 'message': msg }) all_events[ev_obj.EventType][ ev_obj.SourceName]['count'] += 1 except Exception as e: print e
msg = msg.encode('GB18030') log_time = ev_obj.TimeGenerated.Format() log_time = log_time.split()[0] log_time = datetime.datetime.strptime(log_time,'%m/%d/%y') now_time = datetime.datetime.now() day = now_time - log_time if day.days <= 7: if len(msg): if all_events.has_key(ev_obj.EventType): if not all_events[ev_obj.EventType].has_key(ev_obj.SourceName): all_events[ev_obj.EventType][ev_obj.SourceName] = {} if not all_events[ev_obj.EventType][ev_obj.SourceName].has_key(winerror.HRESULT_CODE(ev_obj.EventID)): all_events[ev_obj.EventType][ev_obj.SourceName][winerror.HRESULT_CODE(ev_obj.EventID)] = {'data':None,'count':0} #print day.days all_events[ev_obj.EventType][ev_obj.SourceName][winerror.HRESULT_CODE(ev_obj.EventID)]['data'] = { 'SourceName' : str(ev_obj.SourceName), 'event_level' : ev_obj.EventType, 'event_id' : winerror.HRESULT_CODE(ev_obj.EventID), # 'time' : ev_obj.TimeGenerated.Format(), #'12/23/99 15:54:09' 'hostname' : str(ev_obj.ComputerName), 'message' : msg} all_events[ev_obj.EventType][ev_obj.SourceName][winerror.HRESULT_CODE(ev_obj.EventID)]['count'] += 1 except: pass
def scan_one_audit_log(path_event_log, backup_flag=True): flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ list_id = [4656, 4663, 4660, 4659] try: if backup_flag: handle = win32evtlog.OpenBackupEventLog(None, path_event_log) else: handle = win32evtlog.OpenEventLog(None, "Security") num_records = win32evtlog.GetNumberOfEventLogRecords(handle) total = 0 pending_delete = {} alert_dict = {} events = 1 # Object while events: events = win32evtlog.ReadEventLog(handle, flags, 0) for event in events: event_category = event.EventCategory # ID of event event_id = winerror.HRESULT_CODE(event.EventID) # Category: File System if event_category == 12800 and filter_id(event_id, list_id): # Time generated event event_time = event.TimeGenerated.strftime( '%Y-%m-%d %H:%M:%S') event_computer = str(event.ComputerName) event_user = event.StringInserts[1] event_object = event.StringInserts[6] alert_dict['time'] = event_time alert_dict['user'] = event_user alert_dict['domain'] = event_computer alert_dict['resource'] = event_object # A handle was requested. if event_id == 4656 and has_key(event_object, pending_delete): # The file was not deleted -> created/modified pending_delete[event_object]['alive'] = True # Event 4663 = object access. elif event_id == 4663: event_access_mask = event.StringInserts[9] # 0x10000 = Delete, but this can mean different things - delete, overwrite, rename, move. if event_access_mask == '0x10000' and not is_contain_str( "RECYCLE.BIN", event_object): # Ignore metadata files in the recycle bin. if has_key(event_object, pending_delete): # Is it already in the list? If so, kick it out and replace it. # The most recent handle is used to track a moved file. del pending_delete[event_object] # Record the filename, username, handle ID, and time. pending_delete[event_object] = {} pending_delete[event_object]['user'] = event_user pending_delete[event_object][ 'handle_id'] = event.StringInserts[7] pending_delete[event_object][ 'time_created'] = event_time pending_delete[event_object]['alive'] = False pending_delete[event_object]['confirmed'] = False # 0x2 = is a classic "object was modified" signal. if event_access_mask == '0x2' and not is_contain_str( "RECYCLE.BIN", event_object): # Generate report alert_dict['action'] = ADD_FILE_ACTION_MSG alert_dict['note'] = '0x2' print( "Time: %s, User: %s, Domain: %s, Action: %s, Resource: %s, AccessMask: %s." % (event_time, event_user, event_computer, ADD_FILE_ACTION_MSG, event_object, "0x2")) insert_alert_monitor(alert_dict) # The file was not actually deleted, so remove it from this array. try: del pending_delete[event_object] except (Exception, ValueError): continue # A 4663 event with 0x80 (Read Attributes) is logged # with the same handle ID when files/folders are moved or renamed. if event_access_mask == '0x80': for key in pending_delete.keys(): # If the Handle & User match...and the object wasn't deleted... # figure out whether it was moved or renamed. if pending_delete[key]['handle_id'] == event.StringInserts[7] \ and pending_delete[key]['user'] == event_user \ and event_object != key \ and not pending_delete[key]['confirmed']: # Files moved to a different folder (same filename, different folder) if get_file_name(event_object ) == get_file_name(key): alert_dict[ 'action'] = MOVE_FILE_ACTION_MSG alert_dict['note'] = '0x2' print( "Time: %s, User: %s, Domain: %s, Action: %s, Resource: %s, AccessMask: %s." % (event_time, event_user, event_computer, MOVE_FILE_ACTION_MSG, event_object, "0x2")) insert_alert_monitor(alert_dict) del pending_delete[key] # Files moved into the recycle bin elif is_contain_str( 'RECYCLE.BIN', event_object): alert_dict[ 'action'] = RECYCLE_FILE_ACTION_MSG alert_dict['note'] = '0x2' print( "Time: %s, User: %s, Domain: %s, Action: %s, Resource: %s, AccessMask: %s." % (event_time, event_user, event_computer, RECYCLE_FILE_ACTION_MSG, event_object, "0x2")) insert_alert_monitor(alert_dict) del pending_delete[key] # Files moved out of the recycle bin elif is_contain_str('RECYCLE.BIN', key): alert_dict[ 'action'] = RESTORE_FILE_ACTION_MSG alert_dict['note'] = '0x2' print( "Time: %s, User: %s, Domain: %s, Action: %s, Resource: %s, AccessMask: %s." % (event_time, event_user, event_computer, RESTORE_FILE_ACTION_MSG, event_object, "0x2")) insert_alert_monitor(alert_dict) del pending_delete[key] # Created / renamed files elif get_folder_name( event_object) == get_folder_name( key): if get_file_name(key) == "New Folder": alert_dict[ 'action'] = ADD_FILE_ACTION_MSG alert_dict['note'] = '' print( "Time: %s, User: %s, Domain: %s, Action: %s, Resource: %s, AccessMask: %s." % (event_time, event_user, event_computer, ADD_FILE_ACTION_MSG, event_object, "")) else: alert_dict[ 'action'] = RENAME_FILE_ACTION_MSG alert_dict['note'] = '' print( "Time: %s, User: %s, Domain: %s, Action: %s, Resource: %s, AccessMask: %s." % (event_time, event_user, event_computer, RENAME_FILE_ACTION_MSG, key, "")) insert_alert_monitor(alert_dict) del pending_delete[key] break # If none of those conditions match, at least note that the file still exists (if applicable). if has_key(event_object, pending_delete): pending_delete[event_object]['alive'] = True # Event 4659 = a handle was requested with intent to delete elif event_id == 4659: alert_dict['action'] = DELETE_FILE_ACTION_MSG alert_dict['note'] = '' print( "Time: %s, User: %s, Domain: %s, Action: %s, Resource: %s, AccessMask: %s." % (event_time, event_user, event_computer, DELETE_FILE_ACTION_MSG, event_object, "")) insert_alert_monitor(alert_dict) # This delete confirmation doesn't happen when objects are moved/renamed; # it does when files are created/deleted/recycled. elif event_id == 4660: for key in pending_delete.keys(): # print(event.StringInserts[5], pending_delete[key]['handle_id']) if pending_delete[key]['handle_id'] == event.StringInserts[5] \ and pending_delete[key]['user'] == event_user: pending_delete[key]['confirmed'] = True # msg = win32evtlogutil.SafeFormatMessage(event, log_type) total = total + len(events) win32evtlog.CloseEventLog(handle) msg = "Done read event_log. Scan: " + str(total) + "/" + str( num_records) + "." return SUCCESS_CODE, msg except Exception as e: print(e, 123) return ERROR_CODE, "Cannot read windows event_log."
message = '\n'.join(ev_obj.StringInserts) user = '' if ev_obj.Sid is not None: try: domain, domain_user, _ = LookupAccountSid(server, ev_obj.Sid) user = u'{}\\{}'.format(domain, domain_user) except error: user = str(ev_obj.Sid) if not message: continue yield { 'id': int(winerror.HRESULT_CODE(ev_obj.EventID)) + UTC_OFFSET_TIMEDELTA, 'EventID': int(winerror.HRESULT_CODE(ev_obj.EventID)), 'record': ev_obj.RecordNumber, 'date': int(ev_obj.TimeGenerated), 'computer': ev_obj.ComputerName, 'category': ev_obj.EventCategory, 'msg': message, 'source': logtype + ': ' + ev_obj.SourceName, 'type': EventLog.event_types.get(ev_obj.EventType, 'UNKNOWN'), 'user': user } except GeneratorExit: pass finally: for source in self._formatters_cache.keys():
def getEventLogs(companyId, logtype, eventIDs, path, needDaySpace): """ Get the event logs from the specified machine according to the logtype (Example: Application) and save it to the appropriately named log file """ print("载入%s事件" % logtype) # 读取本机的,system系统日志 hand = win32evtlog.OpenEventLog(None, logtype) # 获取system日志的总行数 total = win32evtlog.GetNumberOfEventLogRecords(hand) print("%s总日志数量为%s" % (logtype, total)) flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ events = win32evtlog.ReadEventLog(hand, flags, 0) # 错误级别类型 # evt_dict = {win32con.EVENTLOG_AUDIT_FAILURE: 'EVENTLOG_AUDIT_FAILURE', # win32con.EVENTLOG_AUDIT_SUCCESS: 'EVENTLOG_AUDIT_SUCCESS', # win32con.EVENTLOG_INFORMATION_TYPE: 'EVENTLOG_INFORMATION_TYPE', # win32con.EVENTLOG_WARNING_TYPE: 'EVENTLOG_WARNING_TYPE', # win32con.EVENTLOG_ERROR_TYPE: 'EVENTLOG_ERROR_TYPE'} evt_dict = { win32con.EVENTLOG_WARNING_TYPE: '警告', win32con.EVENTLOG_ERROR_TYPE: '错误', win32con.EVENTLOG_AUDIT_FAILURE: '审核失败', win32con.EVENTLOG_AUDIT_SUCCESS: '审核成功', win32con.EVENTLOG_INFORMATION_TYPE: '信息' } try: events = 1 log = codecs.open(path, encoding='utf-8', mode='w') while events: events = win32evtlog.ReadEventLog(hand, flags, 0) for ev_obj in events: the_time = ev_obj.TimeGenerated.Format() # '12/23/99 15:54:09' time_obj = datetime.strptime(the_time, '%c') evt_id = int(winerror.HRESULT_CODE(ev_obj.EventID)) computer = str(ev_obj.ComputerName) cat = ev_obj.EventCategory # seconds=date2sec(the_time) record = ev_obj.RecordNumber try: msg = win32evtlogutil.SafeFormatMessage(ev_obj, logtype) except: msg = '' source = str(ev_obj.SourceName) nowtime = datetime.today() daySpace = nowtime.__sub__(time_obj).days if not ev_obj.EventType in evt_dict.keys(): evt_type = "未知" else: evt_type = str(evt_dict[ev_obj.EventType]) if evt_type in eventType and str(evt_id) in eventIDs and int( daySpace) <= int(needDaySpace): detailIniPath = 'detail.ini' if not os.path.exists(detailIniPath): detaiconfig = configparser.ConfigParser() detaiconfig['{}'.format(evt_id)] = { 'evt_id': evt_id, 'evt_type': evt_type, 'source': source, 'msg': msg.strip(), 'detail': { time_obj.strftime("%Y-%m-%d %H:%M"): record }, "sentstatus": '' } with open(detailIniPath, 'w', encoding='utf-8') as detailIniPath: detaiconfig.write(detailIniPath) else: detaiconfig = configparser.ConfigParser() detaiconfig.read("detail.ini", encoding="utf-8") if detaiconfig.has_section(str(evt_id)): detail = eval(detaiconfig[str(evt_id)]['detail']) if time_obj.strftime( "%Y-%m-%d %H:%M") not in detail.keys(): detail[time_obj.strftime( "%Y-%m-%d %H:%M")] = record detaiconfig.set(str(evt_id), 'detail', str(detail)) with open(detailIniPath, 'w', encoding='utf-8') as detailIniPath: detaiconfig.write(detailIniPath) else: detaiconfig.add_section(str(evt_id)) detaiconfig.set(str(evt_id), 'evt_id', str(evt_id)) detaiconfig.set(str(evt_id), 'evt_type', evt_type) detaiconfig.set(str(evt_id), 'source', source) detaiconfig.set(str(evt_id), 'msg', msg.strip()) detaiconfig.set( str(evt_id), 'detail', str({ time_obj.strftime("%Y-%m-%d %H:%M"): record })) detaiconfig.set(str(evt_id), 'sentstatus', '') with open(detailIniPath, 'w', encoding='utf-8') as detailIniPath: detaiconfig.write(detailIniPath) log.write("计算机名:%s" % computer) log.write("记录编码:%s" % record) log.write("事件时间: %s" % time_obj) log.write("事件ID:%s | 事件类别: %s" % (evt_id, evt_type)) log.write("来源: %s" % source) log.write(msg + '') except: print(traceback.print_exc(sys.exc_info())) print("日志文件创建完成:%s" % path) print("")
def create_logs(ipaddr, log_type): """reads windows event logs of type specified by log_type for machine specified by ipaddr and returns in a tuple array Args: ipaddr (str): machine ip address log_type (str): System|Application|Security (see LOG_TYPE_* constants) """ logs = lxml.etree.Element(TAG_LOGS) logs.set(ATTRIBUTE_TYPE, log_type) # following packages (from win32api) are not available on platforms other than windows try: import win32con import win32evtlog import win32evtlogutil import winerror except ImportError: # current platform is not Windows return logs try: hand = win32evtlog.OpenEventLog(ipaddr, log_type) except Exception as error: # pragma no cover print('Exception in win32evtlog.OpenEventLog: {error}'.format( error=error)) return logs #total = win32evtlog.GetNumberOfEventLogRecords(hand) flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ events = win32evtlog.ReadEventLog(hand, flags, 0) event_map = { win32con.EVENTLOG_AUDIT_FAILURE: 'EVENTLOG_AUDIT_FAILURE', win32con.EVENTLOG_AUDIT_SUCCESS: 'EVENTLOG_AUDIT_SUCCESS', win32con.EVENTLOG_INFORMATION_TYPE: 'EVENTLOG_INFORMATION_TYPE', win32con.EVENTLOG_WARNING_TYPE: 'EVENTLOG_WARNING_TYPE', win32con.EVENTLOG_ERROR_TYPE: 'EVENTLOG_ERROR_TYPE', } while events: events = win32evtlog.ReadEventLog(hand, flags, 0) for event in events: try: event_id = str(winerror.HRESULT_CODE(event.EventID)) event_time = event.TimeGenerated.Format() event_computer_name = event.ComputerName event_category = str(event.EventCategory) event_type = event_map.get(event.EventType, 'unknown') event_source_name = event.SourceName event_record_number = str(event.RecordNumber) event_message = win32evtlogutil.SafeFormatMessage( event, log_type) node = lxml.etree.Element(TAG_LOG) node.set(ATTRIBUTE_LOG_ID, event_id) node.set(ATTRIBUTE_EVENT_TIME, event_time) node.set(ATTRIBUTE_COMPUTER_NAME, event_computer_name) node.set(ATTRIBUTE_CATEGORY, event_category) node.set(ATTRIBUTE_RECORD_NUMBER, event_record_number) node.set(ATTRIBUTE_SOURCE_NAME, event_source_name) node.set(ATTRIBUTE_EVENT_TYPE, event_type) node.set(ATTRIBUTE_MESSAGE, event_message) logs.append(node) except Exception as error: # pragma no cover print('Exception in win32evtlog.ReadEventLog.loop: {error}'. format(error=error)) return logs
def get_eventlog(logtype, last_n_days): start_time = datetime.datetime.now() - datetime.timedelta(days=last_n_days) flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ status_dict = { win32con.EVENTLOG_AUDIT_FAILURE: "AUDIT_FAILURE", win32con.EVENTLOG_AUDIT_SUCCESS: "AUDIT_SUCCESS", win32con.EVENTLOG_INFORMATION_TYPE: "INFO", win32con.EVENTLOG_WARNING_TYPE: "WARNING", win32con.EVENTLOG_ERROR_TYPE: "ERROR", 0: "INFO", } computer = "localhost" hand = win32evtlog.OpenEventLog(computer, logtype) total = win32evtlog.GetNumberOfEventLogRecords(hand) log = [] uid = 0 done = False try: while 1: events = win32evtlog.ReadEventLog(hand, flags, 0) for ev_obj in events: uid += 1 # return once total number of events reach or we'll be stuck in an infinite loop if uid >= total: done = True break the_time = ev_obj.TimeGenerated.Format() time_obj = datetime.datetime.strptime(the_time, "%c") if time_obj < start_time: done = True break computer = str(ev_obj.ComputerName) src = str(ev_obj.SourceName) evt_type = str(status_dict[ev_obj.EventType]) evt_id = str(winerror.HRESULT_CODE(ev_obj.EventID)) evt_category = str(ev_obj.EventCategory) record = str(ev_obj.RecordNumber) msg = (str(win32evtlogutil.SafeFormatMessage( ev_obj, logtype)).replace("<", "").replace(">", "")) event_dict = { "computer": computer, "source": src, "eventType": evt_type, "eventID": evt_id, "eventCategory": evt_category, "message": msg, "time": the_time, "record": record, "uid": uid, } log.append(event_dict) if done: break except Exception: pass win32evtlog.CloseEventLog(hand) return _compress_json(log)
def get_eventlog(logtype, last_n_days): start_time = datetime.datetime.now() - datetime.timedelta(days=last_n_days) flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ status_dict = { win32con.EVENTLOG_AUDIT_FAILURE: "AUDIT_FAILURE", win32con.EVENTLOG_AUDIT_SUCCESS: "AUDIT_SUCCESS", win32con.EVENTLOG_INFORMATION_TYPE: "INFO", win32con.EVENTLOG_WARNING_TYPE: "WARNING", win32con.EVENTLOG_ERROR_TYPE: "ERROR", 0: "INFO", } computer = "localhost" hand = win32evtlog.OpenEventLog(computer, logtype) log = [] try: events = 1 while events: events = win32evtlog.ReadEventLog(hand, flags, 0) for ev_obj in events: the_time = ev_obj.TimeGenerated.Format() time_obj = datetime.datetime.strptime(the_time, "%c") if time_obj < start_time: break computer = str(ev_obj.ComputerName) src = str(ev_obj.SourceName) evt_type = str(status_dict[ev_obj.EventType]) evt_id = str(winerror.HRESULT_CODE(ev_obj.EventID)) evt_category = str(ev_obj.EventCategory) record = str(ev_obj.RecordNumber) msg = str(win32evtlogutil.SafeFormatMessage(ev_obj, logtype)) event_dict = { "computer": computer, "source": src, "eventType": evt_type, "eventID": evt_id, "eventCategory": evt_category, "message": msg, "time": the_time, "record": record, "uid": "".join( [ random.choice(string.ascii_letters + string.digits) for n in range(60) ] ), } log.append(event_dict) if time_obj < start_time: break except Exception as e: pass win32evtlog.CloseEventLog(hand) return log
while 1: events = win32evtlog.ReadEventLog(system_handle, flags, 0) # print type(events) if not events: break # print events k = k + 1 #if k==30: # break #for k in events: #print type(k) for ev_obj in events: # print 'this is ev_obj %s'%type(ev_obj) the_time = ev_obj.TimeGenerated.Format() #'12/23/99 15:54:09' # print the_time evt_id = str(winerror.HRESULT_CODE(ev_obj.EventID)) # print 'this is events_id %s'%ev_obj.EventID # print 'event-type is %d'%ev_obj.EventType computer = str(ev_obj.ComputerName) cat = ev_obj.EventCategory record = ev_obj.RecordNumber msg = win32evtlogutil.SafeFormatMessage(ev_obj, 'System') msg = msg.encode('GB18030') if ev_obj.EventType == 0: #L.append(ev_obj.EventType) L.append(ev_obj.EventID) print msg print ev_obj.EventID print ev_obj.EventType print the_time print 'service_name is %s ' % ev_obj.SourceName