當前位置: 首頁>>代碼示例>>Python>>正文


Python win32evtlog.OpenEventLog方法代碼示例

本文整理匯總了Python中win32evtlog.OpenEventLog方法的典型用法代碼示例。如果您正苦於以下問題:Python win32evtlog.OpenEventLog方法的具體用法?Python win32evtlog.OpenEventLog怎麽用?Python win32evtlog.OpenEventLog使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在win32evtlog的用法示例。


在下文中一共展示了win32evtlog.OpenEventLog方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: BackupClearLog

# 需要導入模塊: import win32evtlog [as 別名]
# 或者: from win32evtlog import OpenEventLog [as 別名]
def BackupClearLog(logType):
	datePrefix = time.strftime("%Y%m%d", time.localtime(time.time()))
	fileExists = 1
	retry = 0
	while fileExists:
		if retry == 0:
			index = ""
		else:
			index = "-%d" % retry
		try:
			fname = os.path.join(win32api.GetTempPath(), "%s%s-%s" % (datePrefix, index, logType) + ".evt")
			os.stat(fname)
		except os.error:
			fileExists = 0
		retry = retry + 1
	# OK - have unique file name.
	try:
		hlog = win32evtlog.OpenEventLog(None, logType)
	except win32evtlogutil.error, details:
		print "Could not open the event log", details
		return 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:23,代碼來源:backupEventLog.py

示例2: test_basic

# 需要導入模塊: import win32evtlog [as 別名]
# 或者: from win32evtlog import OpenEventLog [as 別名]
def test_basic(self):
        logtype = 'Application'
        elh = win32evtlog.OpenEventLog(None, logtype)
        num_recs = win32evtlog.GetNumberOfEventLogRecords(elh)

        try:
            h = logging.handlers.NTEventLogHandler('test_logging')
        except pywintypes.error as e:
            if e.winerror == 5:  # access denied
                raise unittest.SkipTest('Insufficient privileges to run test')
            raise

        r = logging.makeLogRecord({'msg': 'Test Log Message'})
        h.handle(r)
        h.close()
        # Now see if the event is recorded
        self.assertLess(num_recs, win32evtlog.GetNumberOfEventLogRecords(elh))
        flags = win32evtlog.EVENTLOG_BACKWARDS_READ | \
                win32evtlog.EVENTLOG_SEQUENTIAL_READ
        found = False
        GO_BACK = 100
        events = win32evtlog.ReadEventLog(elh, flags, GO_BACK)
        for e in events:
            if e.SourceName != 'test_logging':
                continue
            msg = win32evtlogutil.SafeFormatMessage(e, logtype)
            if msg != 'Test Log Message\r\n':
                continue
            found = True
            break
        msg = 'Record not found in event log, went back %d records' % GO_BACK
        self.assertTrue(found, msg=msg)

# Set the locale to the platform-dependent default.  I have no idea
# why the test does this, but in any case we save the current locale
# first and restore it at the end. 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:38,代碼來源:test_logging.py

示例3: ReadLog

# 需要導入模塊: import win32evtlog [as 別名]
# 或者: from win32evtlog import OpenEventLog [as 別名]
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) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:43,代碼來源:eventLogDemo.py

示例4: FeedEventLogRecords

# 需要導入模塊: import win32evtlog [as 別名]
# 或者: from win32evtlog import OpenEventLog [as 別名]
def FeedEventLogRecords(feeder, machineName = None, logName = "Application", readFlags = None):
    if readFlags is None:
        readFlags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ

    h=win32evtlog.OpenEventLog(machineName, logName)
    try:
        while 1:
            objects = win32evtlog.ReadEventLog(h, readFlags, 0)
            if not objects:
                break
            map(lambda item, feeder = feeder: feeder(*(item,)), objects)
    finally:
        win32evtlog.CloseEventLog(h) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:15,代碼來源:win32evtlogutil.py

示例5: _list_evt_xp

# 需要導入模塊: import win32evtlog [as 別名]
# 或者: from win32evtlog import OpenEventLog [as 別名]
def _list_evt_xp(self, server, logtype):
        """Retrieves the contents of the event log for Windows XP"""
        self.logger.info('Exporting logs for : ' + logtype)
        hand = win32evtlog.OpenEventLog(server, logtype)
        flags = win32evtlog.EVENTLOG_FORWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
        total = win32evtlog.GetNumberOfEventLogRecords(hand)
        sum_evt = 0
        while True:
            events = win32evtlog.ReadEventLog(hand, flags, 0)
            sum_evt += len(events)
            if events:
                for event in events:
                    data = event.StringInserts
                    date = datetime.datetime(event.TimeGenerated.year, event.TimeGenerated.month,
                                             event.TimeGenerated.day, event.TimeGenerated.hour,
                                             event.TimeGenerated.minute, event.TimeGenerated.second).strftime(
                        '%d/%m/%Y %H:%M:%S')

                    # print date + ' : ' + log_type + ' -> ' + log_data
                    if data:
                        yield unicode(event.EventCategory), unicode(event.SourceName), unicode(event.EventID), unicode(
                            event.EventType), date, list(data)
                    else:
                        yield unicode(event.EventCategory), unicode(event.SourceName), unicode(event.EventID), unicode(
                            event.EventType), date, []
            if sum_evt >= total:
                break 
開發者ID:SekoiaLab,項目名稱:Fastir_Collector,代碼行數:29,代碼來源:logs.py

示例6: __read_from_event_log

# 需要導入模塊: import win32evtlog [as 別名]
# 或者: from win32evtlog import OpenEventLog [as 別名]
def __read_from_event_log(self, source, event_types):

        event_log = win32evtlog.OpenEventLog(self._server, source)
        if not event_log:
            self._logger.error("Unknown error opening event log for '%s'" % source)
            return

        # we read events in reverse from the end of the log to avoid problems when
        # seeking directly to a record in a large log file
        flags = (
            win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
        )

        offset = -1

        # use the checkpoint if it exists
        if source in self._checkpoints:
            offset = self._checkpoints[source]

        # a list of events that we haven't yet seen
        event_list = []
        try:
            events = True
            while events:
                events = win32evtlog.ReadEventLog(event_log, flags, offset)
                for event in events:
                    # special case for when there was no offset, in which case
                    # the first event will be the latest event so use that for the
                    # new offset
                    if offset == -1:
                        self._checkpoints[source] = event.RecordNumber
                        events = False
                        break
                    # if we encounter our last seen record, then we are done
                    elif (
                        offset == event.RecordNumber
                        or len(event_list) >= self._maximum_records
                    ):
                        events = False
                        break
                    else:
                        # add the event to our list of interested events
                        # if it is one we are interested in
                        if event.EventType in event_types:
                            event_list.append(event)
        except Exception as error:
            self._logger.error(
                "Error reading from event log: %s",
                six.text_type(error),
                limit_once_per_x_secs=self._error_repeat_interval,
                limit_key="EventLogError",
            )

        # now print out records in reverse order (which will put them in correct chronological order
        # because we initially read them in reverse)
        for event in reversed(event_list):
            self.__log_event(source, event)
            self._checkpoints[source] = event.RecordNumber 
開發者ID:scalyr,項目名稱:scalyr-agent-2,代碼行數:60,代碼來源:windows_event_log_monitor.py

示例7: AddSourceToRegistry

# 需要導入模塊: import win32evtlog [as 別名]
# 或者: from win32evtlog import OpenEventLog [as 別名]
def AddSourceToRegistry(appName, msgDLL = None, eventLogType = "Application", eventLogFlags = None):
    """Add a source of messages to the event log.

    Allows Python program to register a custom source of messages in the
    registry.  You must also provide the DLL name that has the message table, so the
    full message text appears in the event log.

    Note that the win32evtlog.pyd file has a number of string entries with just "%1"
    built in, so many Python programs can simply use this DLL.  Disadvantages are that
    you do not get language translation, and the full text is stored in the event log,
    blowing the size of the log up.
    """

    # When an application uses the RegisterEventSource or OpenEventLog
    # function to get a handle of an event log, the event loggging service
    # searches for the specified source name in the registry. You can add a
    # new source name to the registry by opening a new registry subkey
    # under the Application key and adding registry values to the new
    # subkey.

    if msgDLL is None:
        msgDLL = win32evtlog.__file__

    # Create a new key for our application
    hkey = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, \
        "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (eventLogType, appName))

    # Add the Event-ID message-file name to the subkey.
    win32api.RegSetValueEx(hkey,
        "EventMessageFile",    # value name \
        0,                     # reserved \
        win32con.REG_EXPAND_SZ,# value type \
        msgDLL)

    # Set the supported types flags and add it to the subkey.
    if eventLogFlags is None:
        eventLogFlags = win32evtlog.EVENTLOG_ERROR_TYPE | win32evtlog.EVENTLOG_WARNING_TYPE | win32evtlog.EVENTLOG_INFORMATION_TYPE
    win32api.RegSetValueEx(hkey, # subkey handle \
        "TypesSupported",        # value name \
        0,                       # reserved \
        win32con.REG_DWORD,      # value type \
        eventLogFlags)
    win32api.RegCloseKey(hkey) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:45,代碼來源:win32evtlogutil.py


注:本文中的win32evtlog.OpenEventLog方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。