Можно ли получить windows журналов в режиме реального времени за python? - PullRequest
0 голосов
/ 03 марта 2020

I sh для получения windows журналов в режиме реального времени для анализа. Погуглил кое-что и придумал это.

import win32evtlog # requires pywin32 pre-installed

 server = 'localhost' # name of the target computer to get event logs
logtype = 'System' # 'Application' # 'Security' System
hand = win32evtlog.OpenEventLog(server,logtype)
flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
total = win32evtlog.GetNumberOfEventLogRecords(hand)

while True:
     events = win32evtlog.ReadEventLog(hand, flags,0)
     if events:
          for event in events: 
                print 'Event Category:', event.EventCategory
                print 'Time Generated:', event.TimeGenerated
                print 'Source Name:', event.SourceName
                print 'Event ID:', event.EventID
                print 'Event Type:', event.EventType
                data = event.StringInserts
                if data:
                    print 'Event Data:'
                    for msg in data:
                        print msg\n

Что он делает, так это печатает все журналы с начала до того момента, когда код запускается. Можно ли постоянно отслеживать и печатать журналы при каждом обновлении?

1 Ответ

0 голосов
/ 03 марта 2020

python документы здесь , но они не слишком полезны, поэтому я также посмотрел Microsoft C ++ Docs , в котором образец

Я не мог понять, как получить объект, который вы получили от win32evtlog.ReadEventLog через события, но библиотека позволяет визуализировать в XML, поэтому с помощью синтаксического анализатора XML вы сможете извлечь всю информацию, которую вы нужно:

import win32evtlog
import pprint
import sys

# Subscribes to and logs 'application' events
# To manually fire a new event, open an admin console and type: (replace 125 with any other ID that suits you)
#   eventcreate.exe /L "application" /t warning /id 125 /d "This is a test warning"

# event_context can be `None` if not required, this is just to demonstrate how it works
event_context = { "info": "this object is always passed to your callback" }
# Event log source to listen to
event_source = 'application'

def new_logs_event_handler(reason, context, evt):
  """
  Called when new events are logged.

  reason - reason the event was logged?
  context - context the event handler was registered with
  evt - event handle
  """
  # Just print some information about the event
  print ('reason', reason, 'context', context, 'event handle', evt)

  # Render event to xml, maybe there's a way of getting an object but I didn't find it
  print('Rendered event:', win32evtlog.EvtRender(evt, win32evtlog.EvtRenderEventXml))

  # empty line to separate logs
  print(' - ')

  # Make sure all printed text is actually printed to the console now
  sys.stdout.flush()

  return 0

# Subscribe to future events
subscription = win32evtlog.EvtSubscribe(event_source, win32evtlog.EvtSubscribeToFutureEvents, None, Callback=new_logs_event_handler, Context=event_context, Query=None)

Выход

reason 1 context {'info': 'this object is always passed to your callback'} event handle 1
Rendered event: <Event xmlns='http://schemas.microsoft.com/win/2004/08/events/event'><System><Provider Name='EventCreate'/><EventID Qualifiers='0'>125</EventID><Level>3</Level><Task>0</Task><Keywords>0x80000000000000</Keywords><TimeCreated SystemTime='2020-03-03T15:23:11.150209500Z'/><EventRecordID>1</EventRecordID><Channel>Application</Channel><Computer>mypc</Computer><Security UserID='guid'/></System><EventData><Data>This is a test warning</Data></EventData></Event>
 -
reason 1 context {'info': 'this object is always passed to your callback'} event handle 1
Rendered event: <Event xmlns='http://schemas.microsoft.com/win/2004/08/events/event'><System><Provider Name='EventCreate'/><EventID Qualifiers='0'>125</EventID><Level>3</Level><Task>0</Task><Keywords>0x80000000000000</Keywords><TimeCreated SystemTime='2020-03-03T15:23:17.876041700Z'/><EventRecordID>2</EventRecordID><Channel>Application</Channel><Computer>mypc</Computer><Security UserID='guid'/></System><EventData><Data>This is a test warning 2</Data></EventData></Event>
 -
reason 1 context {'info': 'this object is always passed to your callback'} event handle 1
Rendered event: <Event xmlns='http://schemas.microsoft.com/win/2004/08/events/event'><System><Provider Name='EventCreate'/><EventID Qualifiers='0'>125</EventID><Level>3</Level><Task>0</Task><Keywords>0x80000000000000</Keywords><TimeCreated SystemTime='2020-03-03T15:23:20.476312800Z'/><EventRecordID>3</EventRecordID><Channel>Application</Channel><Computer>mypc</Computer><Security UserID='guid'/></System><EventData><Data>This is a test warning 3</Data></EventData></Event>
 -
...