def Logminer(): ChooseEvtx=input(bold('请选择的日志序号: (1.应用日志;2.安全日志;3.系统日志)\n\n')+Input()) if ChooseEvtx == '1': EvtxPath= r"C:\WINDOWS\System32\Winevt\Logs\Application.evtx" elif ChooseEvtx == '2': EvtxPath= r"C:\WINDOWS\System32\Winevt\Logs\Security.evtx" else: EvtxPath= r"C:\WINDOWS\System32\Winevt\Logs\System.evtx" try:#默认选择&&防止转换失败 EventID=int(input(bold('请输入提取的事件ID: (默认:4624)\n\n')+Input())) except: EventID=4624 try: with open(EvtxPath,'r') as f: with contextlib.closing(mmap.mmap(f.fileno(),0,access=mmap.ACCESS_READ)) as buffer: bufferHeader = FileHeader(buffer,0) for xml, record in evtx_file_xml_view(bufferHeader): InterestEvent(xml,EventID) print(Result+"日志审计完毕……") except: print(Processing+'提示:由于Python权限低无法读取系统文件,需手动复制文件于当前目录,且文件名改为“log.evtx”!') with open(r"./log.evtx",'r') as f:#可写死文件目录结局python权限低导致无法读取系统某些目录 with contextlib.closing(mmap.mmap(f.fileno(),0,access=mmap.ACCESS_READ)) as buffer: bufferHeader = FileHeader(buffer,0) print("") print(Processing+"读取成功,正在检查数据……") for xml, record in evtx_file_xml_view(bufferHeader): InterestEvent(xml,EventID) print(Result+"日志审计完毕……")
def main(): with open(sys.argv[1], 'r') as f: with contextlib.closing( mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) for (i, chunk) in enumerate(fh.chunks()): for template in chunk.templates().values(): print "Template {%s} at chunk %d, offset %s" % \ (template.guid(), i, hex(template.absolute_offset(0x0))) print evtx_template_readable_view(template)
def main(): with open(sys.argv[1], 'r') as f: with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) print "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>" print "<Events>" for chunk in fh.chunks(): for record in chunk.records(): print record.root().xml([]).encode("utf-8") print "</Events>"
def main(): with open(sys.argv[1], 'r') as f: with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) for (i, chunk) in enumerate(fh.chunks()): for template in chunk.templates().values(): print("Template {%s} at chunk %d, offset %s" % \ (template.guid(), i, hex(template.absolute_offset(0x0)))) print(evtx_template_readable_view(template))
def read_evtx_records(evtx_file): ''' Reads an evtx file, extracts the records, and returns them as a generator :param evtx_file: string path to input evtx file :return: generator ''' evtx_file.seek(0) buf = evtx_file.read() fh = FileHeader(buf, 0x0) for chunk in fh.chunks(): for record in chunk.records(): yield record
def main(): with open(sys.argv[1], 'r') as f: with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) for (i, chunk) in enumerate(fh.chunks()): for template in chunk.templates().values(): print "Template {%s} at chunk %d, offset %s" % \ (template.guid(), i, hex(template.absolute_offset(0x0))) # strip leading newline... print template.template_format()[1:] print ""
def main(): with open(sys.argv[1], 'r') as f: with contextlib.closing( mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) for chunk in fh.chunks(): for record in chunk.records(): try: evtx_record_xml_view(record).encode("utf-8") except Exception as e: print str(e) print repr(e) print evtx_record_xml_view(record).encode("utf-8") return
def main(): with open(sys.argv[1], 'r') as f: with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) for chunk in fh.chunks(): for record in chunk.records(): try: evtx_record_xml_view(record).encode("utf-8") except Exception as e: print str(e) print repr(e) print evtx_record_xml_view(record).encode("utf-8") return
def getEventCount(self, filename): if(os.name == 'posix'): log_dir = log_dir_linux else: log_dir = log_dir_windows with open(os.path.join(log_dir, filename), 'r') as f: with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) count = 0 for chunk in fh.chunks(): for record in chunk.records(): count += 1 # print count, "events found" return count
def main(): u = set() with open('System.evtx', 'r') as file_: buffer = mmap.mmap(file_.fileno(), 0, access=mmap.ACCESS_READ) fh = FileHeader(buffer, 0x00) # record holds offset of file. This is a throwaway variable (__) for strxml, record in Evtx.Views.evtx_file_xml_view(fh): xml_dom = minidom.parseString(strxml.replace('\n', '')) # Get root node. All event logs start with an Event tag aka root. event = xml_dom.getElementsByTagName("Event") if event: # list to store all child nodes of Event name = [] for item in event[0].childNodes: #u.add(item.nodeName) name.append(item.nodeName) get_sysTag(xml_dom, name) #print(u) #break buffer.close()
def readLogFile(self, filename): # parser = argparse.ArgumentParser( # description="Dump a binary EVTX file into XML.") # parser.add_argument("--cleanup", action="store_true", # help="Cleanup unused XML entities (slower)"), # parser.add_argument("evtx", type=str, # help="Path to the Windows EVTX event log file") # args = parser.parse_args() if(os.name == 'posix'): log_dir = log_dir_linux else: log_dir = log_dir_windows with open(os.path.join(log_dir, filename), 'r') as f: with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) print "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>" print "<Events>" count = 0 for xml, record in evtx_file_xml_view(fh): print xml count += 1 print "</Events>" print count, "events found"
def main(): final_count = {} evt = input('[1]获取系统安全日志\n[2]获取evtx日志文件\n') if evt == "1": try: query = EventLog.Query("Security", "Event/EventData/Data[@Name='LogonType']") print('<----------start---------->') for event in query: i = event.xml final_count = analyze(i,final_count) except: input('请以管理员的方式打开,按回车键退出') return elif evt == "2": EvtxPath = input('[*]请输入文件路径:') with open(EvtxPath, 'r') as f: with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: print('<----------start---------->') fh = FileHeader(buf, 0) for xml, record in evtx_file_xml_view(fh): final_count = analyze(xml,final_count) file = 'log{}.html'.format(''.join([str(x) for x in time.localtime(int(time.time()))])) with open(file, 'w', encoding='utf-8') as f: f.write(html_head + str(final_count) + "\nlet timeList=" + str(time_list) + html_foot) print(file + "已保存") input('按回车键退出')
def dump_event_log(event_file, xml_format): if os.path.isfile(event_file) is False: print("The log file : " + event_file + " is not found.") return print("USB related event(s) found in the event log :") print("=============================================\n") with open(event_file, 'r') as f: with contextlib.closing( mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) for xml, record in evtx_file_xml_view(fh): root = ET.fromstring(xml) if root[0][1].text == '1003': if xml_format: print xml else: print root[0][7].get( 'SystemTime' ) + " EventID : " + root[0][ 1].text + " Computer : " + root[0][ 12].text + " User SID : " + root[0][13].get( 'UserID' ) + " User : "******"\n"
def ParseEvtx(files): writefile = open("..\\RESULTS\\EventLog.txt", "a+") with Evtx(files) as evtx: total = sum(1 for i in evtx.records()) with open(files, 'r') as f: with contextlib.closing( mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) writefile.write( "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>" ) writefile.write("<Events>") count = 0 for xml, record in evtx_file_xml_view(fh): count += 1 writefile.write(ascii(xml)) bar_len = 55 filled_len = int(round(bar_len * count / float(total))) percents = round(100.0 * count / float(total), 1) bar = '=' * filled_len + '-' * (bar_len - filled_len) sys.stdout.write('[%s] %s%s %s/%s \r' % (bar, percents, '%', count, total)) sys.stdout.flush() writefile.write("</Events>") print print
def printToAscii(buf): fh = FileHeader(buf, 0x0) print("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>") print("<Events>") for xml, record in evtx_file_xml_view(fh): print(ascii(xml)) print("</Events>")
def parse_window_event_viewer(atm): atm.microsoft_event_viewer.file.open(mode='rb') data = atm.microsoft_event_viewer.file.read() fh = FileHeader(data, 0x0) for xml_line, record in evtx_file_xml_view(fh): # get date match = re.search(r'<TimeCreated SystemTime=\".*\"', xml_line) if not match: continue match = re.search(r'\d{2,4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', match.group()) if not match: continue date = match.group() # event record id match = re.search(r'<EventRecordID>\d*', xml_line) if not match: continue match = re.search(r'\d+', match.group()) event_record_id = match.group() # event id match = re.search(r'<EventID Qualifiers="(\d+)?">\d+', xml_line) if not match: continue event_id = match.group().split(">")[1] context = xml_line AtmEventViewerEvent.objects.get_or_create( atm=atm, event_date=date, event_id=event_id, event_record_id=event_record_id, context=context )
def main(): parser = argparse.ArgumentParser( description="Dump the slack space of an EVTX file.") parser.add_argument("evtx", type=str, help="Path to the Windows EVTX event log file") args = parser.parse_args() with open(args.evtx, 'r') as f: with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) for chunk in fh.chunks(): chunk_start = chunk.offset() last_allocated_offset = chunk_start for record in chunk.records(): last_allocated_offset = record.offset() + record.size() sys.stdout.write(buf[last_allocated_offset:chunk_start + 0x10000])
def read_file(self): with open(self.path, 'r') as f: with contextlib.closing( mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0) return fh return None
def import_xml(filename): # 4624 - Login 528 # 4647 - Logoff 551 #[*] Keys: Category, Description, Data, Domain\User, Date&Time, Source, Computer, Time, Date, Type, Event sessions = {} user_sessions = {} count = 0 with open(filename, 'r') as f: print "[*] Reading EVTX file %s" % filename with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) count = 0 for xml, record in evtx_file_xml_view(fh): if (count % 2000) == 0: print "%s records read" % count count +=1 match = eid_regex.search(xml) eid = int(match.group('eid')) session_id = get_data(xml, 'TargetLogonId') # Insert new session in dictionary if sessions.get(session_id, None) == None: sessions[session_id] = {} if eid in EVTX_LOGIN: if session_id: sessions[session_id] = {} else: continue info = {} info['logon_type'] = get_data(xml, 'LogonType') info['eid'] = str(eid) info['ip'] = get_data(xml, 'IpAddress') + ':' + get_data(xml, 'IpPort') info['datetime'] = parse(time_regex.search(xml).group('time')[:-7]) sessions[session_id][str(eid)] = info username = get_data(xml, 'TargetDomainName') + '\\' + get_data(xml, 'TargetUserName') sessions[session_id]['username'] = username elif eid in EVTX_LOGOFF: # Ignore if orphan session if not sessions.get(session_id, None) == None: continue info = {} info['eid'] = str(eid) info['datetime'] = parse(time_regex.search(xml).group('time')[:-7]) sessions[session_id][str(eid)] = info return sessions
def main(): parser = argparse.ArgumentParser( description="Find and Extract Windows Bits Events and output CSV", usage= 'parse_evtx_BITS.py Microsoft-Windows-Bits-Client%4Operational.evtx -n' ) parser.add_argument( "evtx", type=str, help='Microsoft-Windows-Bits-Client%4Operational.evtx ') parser.add_argument("-n", "--NoHeader", default=False, action="store_true", help="Do not print Header") args = parser.parse_args() if not args.NoHeader: print(Bits_Header) with open(args.evtx, 'r') as f: with contextlib.closing( mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) for xml, record in evtx_file_xml_view(fh): soup = BeautifulSoup(xml, "lxml") Date = soup.event.system.timecreated['systemtime'] Date = Date[:-7] EventID = int(soup.event.system.eventid.string) Computer = soup.event.system.computer.string ProcessID = soup.event.system.execution['processid'] ThreadID = soup.event.system.execution['threadid'] if EventID in bits_ids: event_info = "%s,%s,%s,%s,%s,%s," % ( Date, EventID, bits_ids[EventID], Computer, ProcessID, ThreadID) try: event_data = {} for child in soup.eventdata.children: if type(child) is element.Tag: val = child.text.replace(',', ';') event_data[child['name']] = ' '.join( val.split()) event_data_result = [] for value in bits_data: result = event_data.get(value) if result is None: result = '' event_data_result.append(result) output = ((event_info) + ','.join(map(str, event_data_result))) print(output) except: pass
def parse_logs(file_path): xml_data = '' with open(file_path, 'r') as f: with contextlib.closing( mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0) # 遍历事件,创建Event事件 for xml, record in evtx_file_xml_view(fh): xml_data += xml return xml_data # 返回解析后的XML数据
def parse_log_detail(self, filteID): with open(self.path, 'r') as f: with contextlib.closing( mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0) for xml, record in evtx_file_xml_view(fh): # 只输出事件ID为4624的内容 # InterestEvent(xml,4624) for time_create, IpAddress, ip, IpPort, targetUsername, ProcessName in self.filter_event( xml, filteID): self.printer(time_create, IpAddress, IpPort, ip, targetUsername, ProcessName)
def dump_driverframeworks_log(event_file, xml_format): events_list = list() if os.path.isfile(event_file) is False: print("The log file : " + event_file + " is not found.") return print("USB related event(s) found in the event log :") print("=============================================\n") with open(event_file, 'r') as f: with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) for xml, record in evtx_file_xml_view(fh): root = ET.fromstring(xml) if root[0][1].text == '2003' or root[0][1].text == '2004' or root[0][1].text == '2005' or \ root[0][1].text == '2010' or root[0][1].text == '2100' or root[0][1].text == '2102' or \ root[0][1].text == '2105': if xml_format: evt = EventXML(root[0][7].get('SystemTime'), xml) events_list.append(evt) else: evt = Event(root[0][7].get('SystemTime'), root[0][1].text, root[0][12].text, root[0][13].get('UserID'), utils.find_username_by_sid(root[0][13].get('UserID')), str.split(str(root[1][0].tag), "}")[1], str(root[1][0].get('lifetime')), str(root[1][0].get('instance'))) events_list.append(evt) events_list.sort(key=lambda x: x.datetime) if xml_format: for eventxml in events_list: print eventxml.xmlstring else: for event in events_list: print "UTC Time : " + event.datetime print "EventID : " + event.event_id + " | Description : " + event.description + \ " | Computer : " + event.computer_name + " | User SID : " + event.user_sid + \ " | User : "******"Lifetime : " + event.lifetime print event.device_instance_id + "\n" print str(len(events_list)) + " event(s) found."
def eventlog(self, path): """Iterates over the Events contained within the log at the given path. For each Event, yields a XML string. """ self.logger.debug("Parsing Event log file %s.", path) with NamedTemporaryFile(buffering=0) as tempfile: self._filesystem.download(path, tempfile.name) file_header = FileHeader(tempfile.read(), 0) for xml_string, _ in evtx_file_xml_view(file_header): yield xml_string
def main(): parser = argparse.ArgumentParser( description="Dump the structure of an EVTX file.") parser.add_argument("evtx", type=str, help="Path to the Windows EVTX event log file") args = parser.parse_args() with open(args.evtx, 'r') as f: with contextlib.closing( mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) formatter = EvtxFormatter() for line in formatter.format_header(fh): print(line)
def main(): parser = argparse.ArgumentParser( description="Extract Common Windows Account Change Events", usage='parse_evtx_account_changes.py Security.evtx -n') parser.add_argument("evtx", type=str, help='Security.evtx ') parser.add_argument("-n", "--NoHeader", default=False, action="store_true", help="Do not print Header") args = parser.parse_args() header = (','.join(map(str, event_info_names + event_data_names))) if not args.NoHeader: print(header) with open(args.evtx, 'r') as f: with contextlib.closing( mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) for xml, record in evtx_file_xml_view(fh): soup = BeautifulSoup(xml, "lxml") Date = soup.event.system.timecreated['systemtime'] Date = Date[:-7] EventID = int(soup.event.system.eventid.string) Computer = soup.event.system.computer.string if EventID in evtxs: event_info = "%s,%s,%s,%s," % (Date, EventID, evtxs[EventID], Computer) try: event_data = {} for child in soup.eventdata.children: if type(child) is element.Tag: event_data[child['name']] = ' '.join( child.text.split()) event_data_result = [] for value in event_data_names: result = event_data.get(value) if result is None: result = '' event_data_result.append(result) output = ((event_info) + ','.join(map(str, event_data_result))) print(output) except: pass
def parse(filename): bulk_data = [] with open(filename) as infile: with contextlib.closing( mmap.mmap(infile.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) for xml, record in evtx_file_xml_view(fh): contains_event_data = False log_line = EvtxToElk.build_json(xml) bulk_data.append(json.loads(json.dumps(log_line))) return bulk_data
def main(): parser = argparse.ArgumentParser( description="Extract Common Windows Scheduled Tasks Events to CSV") parser.add_argument( "WinEventLog", type=str, help="Path to Microsoft-Windows-TaskScheduler4Operational.evtx") args = parser.parse_args() with open(args.WinEventLog, 'r') as f: print(header) with contextlib.closing( mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) for xml, record in evtx_file_xml_view(fh): soup = BeautifulSoup(xml, "lxml") Date = soup.event.system.timecreated['systemtime'] Date = Date[:-7] EventID = int(soup.event.system.eventid.string) ProcessID = soup.event.system.execution['processid'] ThreadID = soup.event.system.execution['threadid'] EventDataName = soup.eventdata['name'] Keywords = soup.event.system.keywords.string if EventID: event_info = "%s,%s,%s,%s,%s," % \ (Date, EventID, EventDataName, ProcessID, ThreadID) try: event_data = {} for child in soup.eventdata.children: if type(child) is element.Tag: event_data[child['name']] = ' '.join( child.text.split()) event_data_result = [] for value in event_data_names: result = event_data.get(value) if result is None: result = '' event_data_result.append(result) except: pass print((event_info) + ','.join(map(str, event_data_result)))
def main(): parser = argparse.ArgumentParser(prog="evtIdDumper", description="Specify eventID to dump") # parser.add_argument("-f", "--iFile", dest="ifile", type=str, required=True, help="path to the input file") # parser.add_argument("-i", "--evtId", dest="id", type=str, default="all", help="id of the Event to Dump") parser.add_argument("-o", "--oFile", dest="ofile", type=str, required=False, help="path to the output file") args = parser.parse_args() args.ifile = "Security.evtx" args.evtId = "4624" args.ofile = 'security.txt' args.logontype = '10' outFile = False if args.ofile is not None: outFile = open(args.ofile, 'a+') with open(args.ifile, 'r') as f: buf = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) fh = FileHeader(buf, 0x00) hOut = "<?xml version='1.0' encoding='utf-8' standalone='yes' ?><Events>" if outFile: outFile.write(hOut) else: print(hOut) for strxml, record in Evtx.Views.evtx_file_xml_view(fh): xmlDoc = minidom.parseString(strxml.replace("\n", "")) evtId = xmlDoc.getElementsByTagName("EventID")[0].childNodes[0].nodeValue if args.id == 'all': if outFile: outFile.write(xmlDoc.toprettyxml()) else: print(xmlDoc.toprettyxml()) if evtId == args.evtId: if outFile: outFile.write(xmlDoc.toprettyxml()) else: print(xmlDoc.toprettyxml()) buf.close() endTag = "</Events>" if outFile: outFile.write(endTag) else: print(endTag)
def main(): parser = argparse.ArgumentParser( description="Dump a binary EVTX file into XML.") parser.add_argument("--cleanup", action="store_true", help="Cleanup unused XML entities (slower)"), parser.add_argument("evtx", type=str, help="Path to the Windows EVTX event log file") args = parser.parse_args() with open(args.evtx, 'r') as f: with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) print "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>" print "<Events>" for xml, record in evtx_file_xml_view(fh): print xml print "</Events>"
def main(args): taskList = {} with open(args.evtx, 'r') as f: with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) if args.toXml.lower() == "y": printToAscii(buf) taskList = searchEvent(buf) for event in taskList: print "\nEVENT:", event if event == '4776': # Invalid Logon Attempt print "-----: [ Bad Logon Attempt ]" print "----------------------------" if event == '4624': # Successfully Logged on print "-----: [ Successful Logon ]" print "----------------------------" if event == '1102': # Successful Audit print "-----: [ Successful Audit ]" print "----------------------------" if event == '4672': # Special Privledges print "-----: [ Special Privleges ]" print "----------------------------" if event == '4634': # Account Logged Off print "-----: [ Successful Logoff ]" print "----------------------------" for subVent in taskList[event]: print '[{}] {:>20} {:>30} {:>20}'.format(subVent[1], subVent[5], subVent[6], subVent[7]) count = [] for events in taskList: for event in taskList[events]: if events == '4776': count.append(event[5]) print set(count) print len(set(count))
def main(): with open('Security.evtx', 'r') as file_: # memory map the file to improve I/O performances to avoid a separate system # call for each access and does not require copying data between buffers. # use "with contextlib.closing() as m" statement for opening and closing file w/mmap # TODO Create try-except in case the file is empty (Windows will raise an exception). # TODO Cannot create empty mapping on Windows. Unix will be fine. buffer = mmap.mmap(file_.fileno(), 0, access=mmap.ACCESS_READ) fh = FileHeader(buffer, 0x00) # record holds offset of file. This is a throwaway variable (__) for strxml, record in Evtx.Views.evtx_file_xml_view(fh): xml_dom = minidom.parseString(strxml.replace('\n', '')) # get System node names and values get_sys_data(xml_dom) buffer.close()
def searchEvent(buf): taskList = {} fh = FileHeader(buf, 0x0) for xml, Record in evtx_file_xml_view(fh): try: record = toLxml(xml).xpath("/Event/System/EventID")[0].text event = toLxml(xml).xpath("/Event/System/Task")[0].text ctime = toLxml(xml).xpath("/Event/System/TimeCreated")[0].get("SystemTime") taskAction = toLxml(xml).xpath("/Event/EventData/Data") evZro = '' evOne = '' evTwo = '' evThr = '' try: evZro = getZero(xml) except: pass try: evOne = getOne(xml) except: pass try: evTwo = getTwo(xml) except: pass try: evThr = getThree(xml) except: pass if record in taskList: taskList[record].append([record, ctime, event, taskAction, evZro, evOne, evTwo, evThr]) else: taskList[record] = [[record, ctime, event, taskAction, evZro, evOne, evTwo, evThr]] except(etree.XMLSyntaxError, IndexError) as e: continue return taskList
def MyFun(today, level, folder): EvtxPath = "c:/windows/System32/Winevt/Logs/System.evtx" #日志文件的路径 with open(EvtxPath, 'r') as f: with contextlib.closing( mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0) # 构建一个xml文件,根元素是Events print("") print("") # 遍历事件 for xml, record in evtx_file_xml_view(fh): #print(xml) #dom = xml.dom.minidom.parse(xml) xmldoc = minidom.parseString(xml) root = xmldoc.documentElement #print(root.nodeName) #print(root.nodeValue) Provider = root.getElementsByTagName( 'Provider')[0].getAttribute("Name") TimeCreated = root.getElementsByTagName( 'TimeCreated')[0].getAttribute("SystemTime") EventID = root.getElementsByTagName( 'EventID')[0].firstChild.data Computer = root.getElementsByTagName( 'Computer')[0].firstChild.data Level = root.getElementsByTagName('Level')[0].firstChild.data #t0 = root.getElementsByTagName('Keywords') #Provider0=Provider[0] if today in TimeCreated and Level == level: print(TimeCreated[:19], Computer, Provider, Level, EventID) with open(folder + '/' + today + '.log', 'a') as f: f.write(TimeCreated[:19] + ":" + Computer + ":" + Provider + ":" + Level + ":" + EventID + '\n') else: #print (TimeCreated) pass
def main(): with open(sys.argv[1], 'r') as f: with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf: fh = FileHeader(buf, 0x0) print "Information from file header:" print "Format version : %d.%d" % (fh.major_version(), fh.minor_version()) print "Flags : 0x%08x" % (fh.flags()) dirty_string = "clean" if fh.is_dirty(): dirty_string = "dirty" print "File is : %s" % (dirty_string) full_string = "no" if fh.is_full(): full_string = "yes" print "Log is full : %s" % (full_string) print "Current chunk : %d of %d" % (fh.current_chunk_number(), fh.chunk_count()) print "Oldest chunk : %d" % (fh.oldest_chunk() + 1) print "Next record# : %d" % (fh.next_record_number()) checksum_string = "fail" if fh.calculate_checksum() == fh.checksum(): checksum_string = "pass" print "Check sum : %s" % (checksum_string) print "" if fh.is_dirty(): chunk_count = sum([1 for c in fh.chunks() if c.verify()]) last_chunk = None for chunk in fh.chunks(): if not chunk.verify(): continue last_chunk = chunk next_record_num = last_chunk.log_last_record_number() + 1 print "Suspected updated header values (header is dirty):" print "Current chunk : %d of %d" % (chunk_count, chunk_count) print "Next record# : %d" % (next_record_num) print "" print "Information from chunks:" print " Chunk file (first/last) log (first/last) Header Data" print "- ----- --------------------- --------------------- ------ ------" for (i, chunk) in enumerate(fh.chunks(), 1): note_string = " " if i == fh.current_chunk_number() + 1: note_string = "*" elif i == fh.oldest_chunk() + 1: note_string = ">" if not chunk.check_magic(): if chunk.magic() == "\x00\x00\x00\x00\x00\x00\x00\x00": print "%s %4d [EMPTY]" % (note_string, i) else: print "%s %4d [INVALID]" % (note_string, i) continue header_checksum_string = "fail" if chunk.calculate_header_checksum() == chunk.header_checksum(): header_checksum_string = "pass" data_checksum_string = "fail" if chunk.calculate_data_checksum() == chunk.data_checksum(): data_checksum_string = "pass" print "%s %4d %8d %8d %8d %8d %s %s" % \ (note_string, i, chunk.file_first_record_number(), chunk.file_last_record_number(), chunk.log_first_record_number(), chunk.log_last_record_number(), header_checksum_string, data_checksum_string)