-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse_evtx.py
More file actions
73 lines (59 loc) · 2.61 KB
/
Copy pathparse_evtx.py
File metadata and controls
73 lines (59 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
Parsing Windows Event Logs (EVTX) — companion script for the post:
"Python Quick Guide: Parsing Windows Event Logs (EVTX)"
The parsing logic (namespace handling, the get_data helper, the 4625 filter) is
exactly as it appears in the post. The demo adds a Counter summary of failed
logons per source IP — the "few more lines" the post mentions — which makes a
tidy screenshot.
Unlike the other demo scripts this one needs a real .evtx file: it cannot
fabricate a meaningful Windows event log. Export one first, e.g. in an elevated
PowerShell:
wevtutil epl Security C:\\temp\\Security.evtx
Copy it next to this script (or pass a path), then:
pip install python-evtx
python parse_evtx.py C:\\temp\\Security.evtx
"""
import sys
import os
import xml.etree.ElementTree as ET
from collections import Counter
# The namespace every Windows event XML element lives in
NS = {"e": "http://schemas.microsoft.com/win/2004/08/events/event"}
# --- post code: Step 3 helper ------------------------------------------------
def get_data(root, name):
"""Return the text of an EventData/Data element by its Name attribute."""
node = root.find(f"e:EventData/e:Data[@Name='{name}']", NS)
return node.text if node is not None else None
def main(evtx_path):
try:
import Evtx.Evtx as evtx
except ImportError:
print("python-evtx is not installed. Run: pip install python-evtx")
return
if not os.path.exists(evtx_path):
print(f"No such file: {evtx_path}")
print("Export one with: wevtutil epl Security C:\\temp\\Security.evtx")
return
failures_by_ip = Counter()
shown = 0
# --- post code: Step 3 ---------------------------------------------------
with evtx.Evtx(evtx_path) as log:
for record in log.records():
root = ET.fromstring(record.xml())
event_id = root.find("e:System/e:EventID", NS).text
if event_id != "4625": # failed logon only
continue
account = get_data(root, "TargetUserName")
source_ip = get_data(root, "IpAddress")
if shown < 20: # keep the screenshot readable
print(f"Failed logon: account={account} src={source_ip}")
shown += 1
failures_by_ip[source_ip] += 1
print(f"\nTotal failed logons (4625): {sum(failures_by_ip.values())}")
if failures_by_ip:
print("Top source IPs:")
for ip, count in failures_by_ip.most_common(5):
print(f" {ip}: {count}")
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else "Security.evtx"
main(path)