def get_event_log(server, log_type='system'):
    log_handle = win32evtlog.OpenEventLog(server, log_type)

    total_num_records = win32evtlog.GetNumberOfEventLogRecords(log_handle)

    flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ

    print "There are %d records" % total_num_records
    events = 1
    while events:
        events = win32evtlog.ReadEventLog(log_handle, flags, 0)
        for event in events:
            if is_common_event_id(event.EventID):
                print event.EventID
                print event.EventCategory
                print event.TimeGenerated.Format()
                # print event.TimeWritten  # <type 'time'>
                print event.EventType  # win32evtlog.EVENTLOG_ERROR_TYPE,
                print event.ComputerName
                print event.SourceName
                print win32evtlogutil.SafeFormatMessage(event, log_type)  # Event Description
                # print event.StringInserts
                print event.Sid
                if event.Sid is not None:
                    try:
                        domain, user, typ = win32security.LookupAccountSid(server, event.Sid)
                        sidDesc = "%s/%s" % (domain, user)
                    except win32security.error:  # from pywintypes import error
                        sidDesc = str(event.Sid)
                    user_desc = "Event associated with user %s" % (sidDesc,)
                else:
                    user_desc = None
                print user_desc

    win32evtlog.CloseEventLog(log_handle)
Пример #2
0
    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)
Пример #3
0
def is_interesting_event(event, name, filters):
    for log_property in filters:
        if log_property == 'logged_after':
            continue
        restrictions = filters[log_property]
        for restriction in restrictions:
            value = getattr(event, log_property, None)

            # Special for Event ID
            if log_property == "EventID":
                value = str(value & 0x1FFFFFFF)
                if str(restriction) != value:
                    return False

            # Look in message
            if value is None and log_property == 'Message':
                safe = win32evtlogutil.SafeFormatMessage(event, name)
                if not re.search(restriction, safe):
                    return False

            # Do normal ==
            if not value is None:
                if str(restriction) != str(value):
                    return False
    return True
Пример #4
0
    def __log_event(self, source, event):
        """ Emits information about an event to the logfile for this monintor
        """
        event_type = self.__event_types[event.EventType]

        # we need to get the root source e.g. Application in Application/MyApplication
        # to use with SafeFormatMessage
        source = source.split('/')[0]
        event_message = win32evtlogutil.SafeFormatMessage(event, source)
        time_format = "%Y-%m-%d %H:%M:%SZ"

        self._logger.emit_value(
            "EventLog",
            source,
            extra_fields={
                'Source':
                event.SourceName,
                'RecordNumber':
                event.RecordNumber,
                'TimeGenerated':
                time.strftime(time_format,
                              time.gmtime(int(event.TimeGenerated))),
                'TimeWritten':
                time.strftime(time_format,
                              time.gmtime(int(event.TimeWritten))),
                'Type':
                event_type,
                'EventId':
                event.EventID,
                'Category':
                event.EventCategory,
                'EventMsg':
                event_message,
            })
Пример #5
0
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)
Пример #6
0
def normalize_event(event, name):
    safe_log = {}
    safe_log['message'] = win32evtlogutil.SafeFormatMessage(event, name)
    safe_log['event_id'] = str(event.EventID & 0x1FFFFFFF)
    safe_log['computer_name'] = str(event.ComputerName)
    safe_log['category'] = str(event.EventCategory)
    safe_log['severity'] = EVENT_TYPE.get(event.EventType, 'UNKNOWN')
    safe_log['application'] = str(event.SourceName)
    safe_log['time_generated'] = str(event.TimeGenerated)
    return safe_log
Пример #7
0
def PrintEventLogInfo(records, outfile, sourceNames, logtype):
    import win32evtlogutil
    for record in records:
        try:
            for srcname in sourceNames:
                if str(record.SourceName) == srcname:
                    outfile.write('//////////////////////////////////////\n')
                    outfile.write(
                        win32evtlogutil.SafeFormatMessage(
                            record, logtype).encode("mbcs").replace('\r', ''))
        except:
            continue
Пример #8
0
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)
Пример #9
0
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
Пример #10
0
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)
Пример #11
0
 def __init__(self, handle, readflag, logtype, logSourcename):
     self.records = []
     while True:
         records = win32evtlog.ReadEventLog(handle, readflag, 0)
         if not records:
             break
         for record in records:
             if str(record.SourceName) == logSourcename:
                 data = win32evtlogutil.SafeFormatMessage(
                     record, logtype)  #.encode("mbcs").replace('\r', '')
                 self.records.append({
                     'id': record.EventID,
                     'recordId': record.RecordNumber,
                     'data': data,
                     'type': record.EventType,
                     'sid': record.Sid,
                     'strings': len(record.StringInserts)
                 })
Пример #12
0
 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)
Пример #13
0
def getLastExecuted(computer, exeList):
    logType = "Security"
    query = "A new process has been created."
    eventLog = win32evtlog.OpenEventLog(
        computer, logType)  # Object consisting of all records in requested log

    while True:
        # Magic code BEGINS
        objects = win32evtlog.ReadEventLog(
            eventLog, win32evtlog.EVENTLOG_BACKWARDS_READ
            | win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0)
        if not objects:
            break
        # Magic code ENDS
        for object in objects:
            # get it for testing purposes, but don't print it. - Not written by me. No idea what this does
            record = win32evtlogutil.SafeFormatMessage(object, logType)
            try:
                recordLines = record.splitlines()
                if recordLines[0] == query:
                    for i in range(len(recordLines)):
                        if "New Process Name:" in recordLines[i]:
                            for j in range(len(exeList)):
                                if exeList[j].path in recordLines[i]:
                                    if not exeList[
                                            j].checked:  # record list is sorted newest to oldest, so we check to see if the processes last launch time has already been recorded
                                        exeList[j].checked = True
                                        exeList[j].lastLaunch = timeslation(
                                            object.TimeGenerated.Format()
                                        )  # returns a String of the timestamp of the record
                                    break
                            break

            except UnicodeError:
                print("(unicode error printing message: repr() follows...)")
                print(repr(record))

    win32evtlog.CloseEventLog(eventLog)
    return exeList
Пример #14
0
def main():
    all_events = dict()

    for server in servers:
        all_events[server] = dict()
        for log_type in log_types:
            all_events[server][log_type] = readEventLog(server, log_type)

    html_output_file = sys.argv[0].replace('.py', '.html')
    with open(html_output_file, "w") as out:
        locale.setlocale(locale.LC_ALL, 'english-us')

        out.write("""
            <style>
                body {{ Arial, "Helvetica Neue", Helvetica, sans-serif; }}
                table, th, td {{
                    border: 1px solid lightgray;
                }}
                table {{ border-spacing: 10px; }}
                th, td {{
                    border: none;
                }}
                th {{
                  background-color: darkgray;
                  color: yellow;
                }}
                td {{ vertical-align: text-top; }}
                .event-time {{ font-size: 9px; }}
                .event-type {{ font-size: 9px; }}
                .error-count {{ text-align: right; }}
    
            </style>
            We checked the {} logs on {} over the last {} hours.<br/>
        """.format(log_types, servers, number_of_hours_to_look_back))

        out.write("""
            <table>
            <tr>
                <th>Server</th>
                <th>Log</th>
                <th>Source</th>
                <th>Error count</th>
            </tr>
        """)
        for server in all_events:
            for log_type in all_events[server]:
                errors = dict()
                for event in all_events[server][log_type]:
                    if event.SourceName in errors:
                        errors[event.SourceName] += 1
                    else:
                        errors[event.SourceName] = 1

                for error in errors:
                    out.write("""
                        <tr>
                            <td>{}</td>
                            <td>{}</td>
                            <td>{}</td>
                            <td class="error-count">{}</td>
                        </tr>
                    """.format(
                        server, log_type, error,
                        locale.format("%d", errors[error], grouping=True)))

        out.write("""
            <table>
            <tr>
                <th>Server / Log</th>
                <th>Source/Date</th>
                <th>Text</th>
            </tr>
        """)

        for server in all_events:
            out.write('<tr><th colspan=3>{}</th></tr>'.format(server))
            for log_type in all_events[server]:
                for event in all_events[server][log_type]:
                    msg = str(
                        win32evtlogutil.SafeFormatMessage(event, log_type))
                    msg = msg.replace('<', '&lt;')
                    msg = msg.replace('>', '&gt;')
                    if msg == "" or msg == None:
                        for s in event.StringInserts:
                            msg += "x {}<br/>".format(s)

                    out.write("""
                        <tr>
                            <td>{}<br/><span class="event-type">{}</span></td>
                            <td>{}<br/><span class="event-time">{}</span></td>
                            <td>{}</td>
                        </tr>\n""".format(event.ComputerName, log_type,
                                          event.SourceName, event.TimeWritten,
                                          msg))

        out.write("""
            </table>
        """)

    print("Wrote output to {}".format(html_output_file))
Пример #15
0
    async def event_log_check(self, data):
        try:
            log = []

            api_log_name = data["log_name"]
            api_event_id = int(data["event_id"])
            api_event_type = data["event_type"]
            api_fail_when = data["fail_when"]
            api_search_last_days = int(data["search_last_days"])

            try:
                api_event_id_is_wildcard = data["event_id_is_wildcard"]
            except KeyError:
                api_event_id_is_wildcard = False

            if api_search_last_days != 0:
                start_time = dt.datetime.now() - dt.timedelta(days=api_search_last_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",
            }

            hand = win32evtlog.OpenEventLog("localhost", api_log_name)
            total = win32evtlog.GetNumberOfEventLogRecords(hand)
            uid = 0
            done = False

            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 = dt.datetime.strptime(the_time, "%c")

                    if api_search_last_days != 0:
                        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, api_log_name))
                        .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,
                    }

                    if api_event_id_is_wildcard and evt_type == api_event_type:
                        log.append(event_dict)

                    elif int(evt_id) == api_event_id and evt_type == api_event_type:
                        log.append(event_dict)

                if done:
                    break

            win32evtlog.CloseEventLog(hand)

            if api_fail_when == "contains":
                if log:
                    status = "failing"
                    more_info = {"log": log}
                else:
                    status = "passing"
                    more_info = {"log": []}

            elif api_fail_when == "not_contains":
                if log:
                    status = "passing"
                    more_info = {"log": log}
                else:
                    status = "failing"
                    more_info = {"log": []}
            else:
                status = "failing"
                more_info = {"log": []}

            payload = {
                "status": status,
                "extra_details": more_info,
            }

            self.logger.debug(payload)

            resp = requests.patch(
                f"{self.astor.server}/api/v1/{data['id']}/checkrunner/",
                json.dumps(payload),
                headers=self.headers,
                timeout=15,
            )

            if (
                status == "failing"
                and data["assigned_task"]
                and data["assigned_task"]["enabled"]
            ):
                from taskrunner import TaskRunner

                task = TaskRunner(
                    task_pk=data["assigned_task"]["id"],
                    log_level=self.log_level,
                    log_to=self.log_to,
                )
                await task.run_while_in_event_loop()

            return status
        except Exception as e:
            self.logger.debug(e)
            return "failing"
Пример #16
0
def check_eventlog(start_time):
    # Parse Windows EVENT LOG Source
    # Source: http://docs.activestate.com/activepython/3.3/pywin32/Windows_NT_Eventlog.html

    flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ

    # This dict converts the event type into a human readable form
    evt_dict = {
        win32con.EVENTLOG_AUDIT_FAILURE: 'AUDIT_FAILURE',
        win32con.EVENTLOG_AUDIT_SUCCESS: 'AUDIT_SUCCESS',
        win32con.EVENTLOG_INFORMATION_TYPE: 'INFORMATION',
        win32con.EVENTLOG_WARNING_TYPE: 'WARNING',
        win32con.EVENTLOG_ERROR_TYPE: 'ERROR',
        0: 'INFORMATION'
    }
    computer = 'localhost'
    logtype = 'Application'

    # open event log
    hand = win32evtlog.OpenEventLog(computer, logtype)

    log = []
    error_log = []
    try:
        events = 1
        while events:
            events = win32evtlog.ReadEventLog(hand, flags, 0)
            for ev_obj in events:
                the_time = ev_obj.TimeGenerated.Format()
                # '%c' is the locale date and time string format
                time_obj = datetime.datetime.strptime(the_time, '%c')
                #time_obj = datetime.datetime.strptime(the_time, '%m/%d/%y %H:%M:%S')
                if time_obj < start_time:
                    #if time is old than the start time dont grab the data
                    break
                # data is recent enough
                computer = str(ev_obj.ComputerName)
                src = str(ev_obj.SourceName)
                evt_type = str(evt_dict[ev_obj.EventType])
                msg = unicode(
                    win32evtlogutil.SafeFormatMessage(ev_obj, logtype))

                if (src == 'WSH'
                    ):  # Only Append WPKG Logs (WSH - Windows Scripting Host)
                    # Skip suppressed user notification info
                    if not msg.startswith('User notification suppressed.'):
                        log.append(
                            string.join((the_time, computer, src, evt_type,
                                         '\n' + msg), ' : '))
                    # Create additional error log if there are warnings or errors
                    if (evt_type == "ERROR") or (evt_type == "WARNING"):
                        # Only Append Errors and Warnings
                        if "msiexec" in msg:
                            try:
                                exit_code = re.compile(
                                    "\(([0-9]|[0-9]{2}|[0-9]{4})\)").search(
                                        msg).groups()[0]
                                msg = msg + "MSI error ({}): {}".format(
                                    exit_code, msi_exit_dic[exit_code])
                            except (AttributeError, KeyError):
                                print 'Couldnt determine MSI Exit Code'
                        error_log.append(
                            string.join((the_time, computer, src, evt_type,
                                         '\n' + msg), ' : '))

            if time_obj < start_time:
                break  # get out of while loop as well
        win32evtlog.CloseEventLog(hand)
    except:
        print traceback.print_exc(sys.exc_info())
    return log, error_log
Пример #17
0
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
 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
         N.append({
             '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': ev_obj.RecordNumber,  #
             'Eventcategory': ev_obj.EventCategory,
Пример #19
0
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()))
Пример #20
0
def get_event_string(event):
    """
		@event: PyEventLogRecord
		"""
    return str(win32evtlogutil.SafeFormatMessage(event))
Пример #21
0
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
Пример #22
0
import win32evtlog
import win32evtlogutil
from pprint import pprint
from time import sleep
computer = "MyHost"
computer = "DESKTOP-9MI30R1"
logType = "Application"
h = win32evtlog.OpenEventLog(computer, logType)
objects = win32evtlog.ReadEventLog(h, win32evtlog.EVENTLOG_BACKWARDS_READ|
win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0)
while objects:
    for object in objects:
        dir(object)
        #msg = win32evtlogutil.SafeFormatMessage(object, logType).encode("mbcs")
        msg = win32evtlogutil.SafeFormatMessage(object, logType)
        #if (object.EventType==1):
        if (1==1):
            # エラーのみ表示
            print (msg)
        objects = win32evtlog.ReadEventLog(h, win32evtlog.EVENTLOG_BACKWARDS_READ|
win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0)
        sleep(1)
print (u'完了')
Пример #23
0
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("")
Пример #24
0
    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'
        }

        first_day = datetime.date(self.time.year, self.time.month, 1)
        last_day_pre_month = first_day - datetime.timedelta(days=1)
        first_day_of_pre_month = datetime.date(last_day_pre_month.year,
                                               last_day_pre_month.month, 1)

        try:
            events = 1
            while events:
                events = win32evtlog.ReadEventLog(hand, flags, 0)
                for ev_obj in events:
                    the_date = datetime.date(
                        ev_obj.TimeGenerated.year, ev_obj.TimeGenerated.month,
                        ev_obj.TimeGenerated.day)  #.Format("%Y-%m-%d")
                    the_time = ev_obj.TimeGenerated.Format(
                        "%Y-%m-%d %H:%M:%S")  #'12/23/99 15:54:09'
                    evt_id = str(winerror.HRESULT_CODE(
                        ev_obj.EventID))  # 6005,6006,6009
                    if evt_id == '6005' or evt_id == '6006':
                        if the_date >= first_day_of_pre_month and the_date <= last_day_pre_month:
                            # should be filter by the_date
                            computer = str(ev_obj.ComputerName)
                            cat = ev_obj.EventCategory
                            ##seconds=date2sec(the_time)
                            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("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")

                            print("Event ID / Type: %s / %s\n" %
                                  (evt_id, evt_type))
                            self.list_event.append({
                                "computer_ID": self.computer_ID,
                                "eventID": int(evt_id),
                                "reboot_date": the_time,
                                "event_log": msg
                            })
        except:
            print(traceback.print_exc(sys.exc_info()))

        print("Log creation finished. Location of log is %s" % logPath)
Пример #25
0
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)
Пример #26
0
   if True:
     print( 
       #ev_obj.RecordNumber,
       #ev_obj.TimeGenerated,
       #ev_obj.TimeWritten,
       ev_obj.EventID,
       ev_obj.EventType, 
       #ev_obj.EventCategory, 
       #ev_obj.ReservedFlags, 
       #ev_obj.ClosingRecordNumber, 
       #ev_obj.SourceName,
       ev_obj.StringInserts, 
       #ev_obj.Sid, 
       #ev_obj.Data, 
       ev_obj.ComputerName )
     print( win32evtlogutil.SafeFormatMessage(ev_obj, logType))
   #appname, eventid, vnetcategory, eventtype, strings = win32evtlogutil.SafeFormatMessage(ev_obj, logType)
   #appname = win32evtlogutil.FormatMessage(ev_obj, logType)
   #print( type(appname))
   #print( appname )
 except :
 	pass
 finally:
   pass
 '''
 if winerror.HRESULT_CODE(ev_obj.EventID) == 6005:
   print ("%s %s" % ("start", ev_obj.TimeGenerated.Format()))
   print (win32evtlogutil.SafeFormatMessage(ev_obj, logType))
   # print (win32evtlogutil.SafeFormatMessage(ev_obj, logType).encode("mbcs"))
 if winerror.HRESULT_CODE(ev_obj.EventID) == 7001:
   print ("%s %s" % ("start", ev_obj.TimeGenerated.Format()))
Пример #27
0
    win32con.EVENTLOG_INFORMATION_TYPE: 'EVENTLOG_INFORMATION_TYPE',
    win32con.EVENTLOG_WARNING_TYPE: 'EVENTLOG_WARNING_TYPE',
    win32con.EVENTLOG_ERROR_TYPE: 'EVENTLOG_ERROR_TYPE'
}
k = []
j = []
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'
            print the_time
            evt_id = str(winerror.HRESULT_CODE(ev_obj.EventID))
            print ev_obj.EventID
            print ev_obj.EventType
            computer = str(ev_obj.ComputerName)
            cat = ev_obj.EventCategory
            record = ev_obj.RecordNumber
            msg = win32evtlogutil.SafeFormatMessage(ev_obj, 'Security')
            msg = msg.encode('gb2312')
            print msg
            k.append(ev_obj.EventType)

except:
    print 'code problem'
    pass
if i in k:
    if i not in j:
        j.append(i)
				""".format(server, log_type, error, locale.format("%d", errors[error], grouping=True)))

    out.write("""
		<table>
		<tr>
			<th>Server / Log</th>
			<th>Source/Date</th>
			<th>Text</th>
		</tr>
	""")

    for server in all_events:
        out.write('<tr><th colspan=3>{}</th></tr>'.format(server))
        for log_type in all_events[server]:
            for event in all_events[server][log_type]:
                msg = str(win32evtlogutil.SafeFormatMessage(event, log_type))
                msg = msg.replace('<', '&lt;')
                msg = msg.replace('>', '&gt;')
                if msg == "" or msg == None:
                    for s in event.StringInserts:
                        msg += "x {}<br/>".format(s)

                out.write("""
					<tr>
						<td>{}<br/><span class="event-type">{}</span></td>
						<td>{}<br/><span class="event-time">{}</span></td>
						<td>{}</td>
					</tr>\n""".format(event.ComputerName, log_type, event.SourceName, event.TimeWritten, msg))

    out.write("""
		</table>
Пример #29
0
try:
    events = 1
    while events:
        events = win32evtlog.ReadEventLog(hand, flags, 0)
        for ev_obj in events:
            # check if the event is recent enough
            # only want data from last 8hrs
            the_time = ev_obj.TimeGenerated.Format()
            seconds = date2sec(the_time)
            if seconds < begin_sec - 28800: break

            # data is recent enough, so print it out
            computer = str(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 = str(evt_dict[ev_obj.EventType])
            msg = str(win32evtlogutil.SafeFormatMessage(ev_obj, logtype))
            print(
                string.join((the_time, computer, src, cat, record, evt_id,
                             evt_type, msg[0:15]), ':'))

    if seconds < begin_sec - 28800:
        pass

    win32evtlog.CloseEventLog(hand)
except:
    print(traceback.print_exc(sys.exc_info()))