backupEventLog.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # Generate a base file name
  2. import time, os
  3. import win32api
  4. import win32evtlog
  5. def BackupClearLog(logType):
  6. datePrefix = time.strftime("%Y%m%d", time.localtime(time.time()))
  7. fileExists = 1
  8. retry = 0
  9. while fileExists:
  10. if retry == 0:
  11. index = ""
  12. else:
  13. index = "-%d" % retry
  14. try:
  15. fname = os.path.join(win32api.GetTempPath(), "%s%s-%s" % (datePrefix, index, logType) + ".evt")
  16. os.stat(fname)
  17. except os.error:
  18. fileExists = 0
  19. retry = retry + 1
  20. # OK - have unique file name.
  21. try:
  22. hlog = win32evtlog.OpenEventLog(None, logType)
  23. except win32evtlogutil.error as details:
  24. print("Could not open the event log", details)
  25. return
  26. try:
  27. if win32evtlog.GetNumberOfEventLogRecords(hlog)==0:
  28. print("No records in event log %s - not backed up" % logType)
  29. return
  30. win32evtlog.ClearEventLog(hlog, fname)
  31. print("Backed up %s log to %s" % (logType, fname))
  32. finally:
  33. win32evtlog.CloseEventLog(hlog)
  34. if __name__=='__main__':
  35. BackupClearLog("Application")
  36. BackupClearLog("System")
  37. BackupClearLog("Security")