EvtFormatMessage.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import sys
  2. import win32evtlog
  3. def main():
  4. path = 'System'
  5. num_events = 5
  6. if len(sys.argv) > 2:
  7. path = sys.argv[1]
  8. num_events = int(sys.argv[2])
  9. elif len(sys.argv) > 1:
  10. path = sys.argv[1]
  11. query = win32evtlog.EvtQuery(path, win32evtlog.EvtQueryForwardDirection)
  12. events = win32evtlog.EvtNext(query, num_events)
  13. context = win32evtlog.EvtCreateRenderContext(win32evtlog.EvtRenderContextSystem)
  14. for i, event in enumerate(events, 1):
  15. result = win32evtlog.EvtRender(event, win32evtlog.EvtRenderEventValues, Context=context)
  16. print('Event {}'.format(i))
  17. level_value, level_variant = result[win32evtlog.EvtSystemLevel]
  18. if level_variant != win32evtlog.EvtVarTypeNull:
  19. if level_value == 1:
  20. print(' Level: CRITICAL')
  21. elif level_value == 2:
  22. print(' Level: ERROR')
  23. elif level_value == 3:
  24. print(' Level: WARNING')
  25. elif level_value == 4:
  26. print(' Level: INFO')
  27. elif level_value == 5:
  28. print(' Level: VERBOSE')
  29. else:
  30. print(' Level: UNKNOWN')
  31. time_created_value, time_created_variant = result[win32evtlog.EvtSystemTimeCreated]
  32. if time_created_variant != win32evtlog.EvtVarTypeNull:
  33. print(' Timestamp: {}'.format(time_created_value.isoformat()))
  34. computer_value, computer_variant = result[win32evtlog.EvtSystemComputer]
  35. if computer_variant != win32evtlog.EvtVarTypeNull:
  36. print(' FQDN: {}'.format(computer_value))
  37. provider_name_value, provider_name_variant = result[win32evtlog.EvtSystemProviderName]
  38. if provider_name_variant != win32evtlog.EvtVarTypeNull:
  39. print(' Provider: {}'.format(provider_name_value))
  40. try:
  41. metadata = win32evtlog.EvtOpenPublisherMetadata(provider_name_value)
  42. # pywintypes.error: (2, 'EvtOpenPublisherMetadata', 'The system cannot find the file specified.')
  43. except Exception:
  44. pass
  45. else:
  46. try:
  47. message = win32evtlog.EvtFormatMessage(metadata, event, win32evtlog.EvtFormatMessageEvent)
  48. # pywintypes.error: (15027, 'EvtFormatMessage: allocated 0, need buffer of size 0', 'The message resource is present but the message was not found in the message table.')
  49. except Exception:
  50. pass
  51. else:
  52. print(' Message: {}'.format(message))
  53. if __name__=='__main__':
  54. main()