最近要把遠程機器上的事件記錄拿回本地分析,不過不管是直接在事件檢視器另存還是用dumpel.exe備份,都不是很合自己心意。我一時又沒找到更好的工具,不過手裡有python啊。下面是簡單的原始碼,僅滿足自已目前的需要
1 # -*- coding: cp936 -*-
2 def Usage():
3 print '-f windows event log .evt格式備份'
4 print '-o 輸出檔案'
5 print '-logtype event log類型,預設為 Application'
6
7 def Opts(param):
8 import sys, getopt
9 try:
10 opts, args = getopt.getopt(sys.argv[1:], "h?f:o:logtype:")
11 except :
12 Usage()
13 return False
14
15 for opt, val in opts:
16 if opt == '-f':
17 param['f'] = val
18 if opt == '-o':
19 param['o'] = val
20 if opt == '-logtype':
21 param['logtype'] = val
22 if opt in ['-h', '-?']:
23 Usage()
24 return False
25 if(param['f'] == ''):
26 Usage()
27 return False
28 if(param['o'] == ''):
29 param['o'] = param['f'] + ".txt"
30 return True
31
32 def PrintEventLogInfo(records, outfile, sourceNames, logtype):
33 import win32evtlogutil
34 for record in records:
35 try:
36 for srcname in sourceNames:
37 if str(record.SourceName)==srcname:
38 outfile.write('//////////////////////////////////////\n')
39 outfile.write(win32evtlogutil.SafeFormatMessage(record, logtype).encode("mbcs").replace('\r', ''))
40 except:
41 continue;
42
43 def Dump():
44 import win32evtlog
45 param = {'f':'', 'o':'', 'logtype':'Application'}
46 sourceNames = ['ASP.NET 2.0.50727.0', '']
47 if not Opts(param):
48 return
49 h=win32evtlog.OpenBackupEventLog(None, param['f'])
50 flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
51 outfile = open(param['o'], 'w')
52 while True:
53 records=win32evtlog.ReadEventLog(h, flags, 0)
54 if not records:
55 break;
56 PrintEventLogInfo(records, outfile, sourceNames, param['logtype'])
57 win32evtlog.CloseEventLog(h)
58
59 if __name__=='__main__':
60 Dump()
61
62
simpledump.py -f 2006-10-19-app.evt