eventLogDemo.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import win32evtlog
  2. import win32api
  3. import win32con
  4. import win32security # To translate NT Sids to account names.
  5. import win32evtlogutil
  6. def ReadLog(computer, logType="Application", dumpEachRecord = 0):
  7. # read the entire log back.
  8. h=win32evtlog.OpenEventLog(computer, logType)
  9. numRecords = win32evtlog.GetNumberOfEventLogRecords(h)
  10. # print "There are %d records" % numRecords
  11. num=0
  12. while 1:
  13. objects = win32evtlog.ReadEventLog(h, win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0)
  14. if not objects:
  15. break
  16. for object in objects:
  17. # get it for testing purposes, but dont print it.
  18. msg = win32evtlogutil.SafeFormatMessage(object, logType)
  19. if object.Sid is not None:
  20. try:
  21. domain, user, typ = win32security.LookupAccountSid(computer, object.Sid)
  22. sidDesc = "%s/%s" % (domain, user)
  23. except win32security.error:
  24. sidDesc = str(object.Sid)
  25. user_desc = "Event associated with user %s" % (sidDesc,)
  26. else:
  27. user_desc = None
  28. if dumpEachRecord:
  29. print("Event record from %r generated at %s" % (object.SourceName, object.TimeGenerated.Format()))
  30. if user_desc:
  31. print(user_desc)
  32. try:
  33. print(msg)
  34. except UnicodeError:
  35. print("(unicode error printing message: repr() follows...)")
  36. print(repr(msg))
  37. num = num + len(objects)
  38. if numRecords == num:
  39. print("Successfully read all", numRecords, "records")
  40. else:
  41. print("Couldn't get all records - reported %d, but found %d" % (numRecords, num))
  42. print("(Note that some other app may have written records while we were running!)")
  43. win32evtlog.CloseEventLog(h)
  44. def usage():
  45. print("Writes an event to the event log.")
  46. print("-w : Dont write any test records.")
  47. print("-r : Dont read the event log")
  48. print("-c : computerName : Process the log on the specified computer")
  49. print("-v : Verbose")
  50. print("-t : LogType - Use the specified log - default = 'Application'")
  51. def test():
  52. # check if running on Windows NT, if not, display notice and terminate
  53. if win32api.GetVersion() & 0x80000000:
  54. print("This sample only runs on NT")
  55. return
  56. import sys, getopt
  57. opts, args = getopt.getopt(sys.argv[1:], "rwh?c:t:v")
  58. computer = None
  59. do_read = do_write = 1
  60. logType = "Application"
  61. verbose = 0
  62. if len(args)>0:
  63. print("Invalid args")
  64. usage()
  65. return 1
  66. for opt, val in opts:
  67. if opt == '-t':
  68. logType = val
  69. if opt == '-c':
  70. computer = val
  71. if opt in ['-h', '-?']:
  72. usage()
  73. return
  74. if opt=='-r':
  75. do_read = 0
  76. if opt=='-w':
  77. do_write = 0
  78. if opt=='-v':
  79. verbose = verbose + 1
  80. if do_write:
  81. ph=win32api.GetCurrentProcess()
  82. th = win32security.OpenProcessToken(ph,win32con.TOKEN_READ)
  83. my_sid = win32security.GetTokenInformation(th,win32security.TokenUser)[0]
  84. win32evtlogutil.ReportEvent(logType, 2,
  85. strings=["The message text for event 2","Another insert"],
  86. data = "Raw\0Data".encode("ascii"), sid = my_sid)
  87. win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_WARNING_TYPE,
  88. strings=["A warning","An even more dire warning"],
  89. data = "Raw\0Data".encode("ascii"), sid = my_sid)
  90. win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE,
  91. strings=["An info","Too much info"],
  92. data = "Raw\0Data".encode("ascii"), sid = my_sid)
  93. print("Successfully wrote 3 records to the log")
  94. if do_read:
  95. ReadLog(computer, logType, verbose > 0)
  96. if __name__=='__main__':
  97. test()