-
Notifications
You must be signed in to change notification settings - Fork 19
/
pstranscript2eventstream.py
53 lines (46 loc) · 2.18 KB
/
pstranscript2eventstream.py
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
import argparse
import datetime
import json
import re
# Parses a log created with the following powershell command:
# Start-Transcript -path c:\temp\pslog.txt -IncludeInvocationHeader -Append
#
# Or always log with a registry mod: https://adamtheautomator.com/powershell-logging-2/#How_to_Turn_on_Transcripts_with_the_Registry
def dump_to_json(eventstream_file, timestamp, user, host, command, output):
eventstream_file.write(json.dumps({"ts": timestamp.isoformat(), "s": {"u": user, "h": host}, "d": command, "output": output.lstrip("\n")}))
eventstream_file.write("\n")
def main(transcript_file, eventstream_file):
local_timezone = datetime.datetime.utcnow().astimezone().tzinfo
in_section = True
command = ""
output = ""
for line in transcript_file:
if line == "**********************\n":
in_section = not in_section
if in_section:
dump_to_json(eventstream_file, timestamp, user, host, command, output)
command = ""
output = ""
elif in_section:
if line.startswith("Command start time: "):
timestamp = datetime.datetime.strptime(line[20:], '%Y%m%d%H%M%S\n')
timestamp = timestamp.replace(tzinfo=local_timezone)
elif line.startswith("Start time: "):
timestamp = datetime.datetime.strptime(line[12:], '%Y%m%d%H%M%S\n')
timestamp = timestamp.replace(tzinfo=local_timezone)
elif line.startswith("Machine: "):
host = re.match(r"Machine: (.+) \(", line)[1]
elif line.startswith("RunAs User: "):
user = re.match(r"RunAs User: .+\\(.+)$", line)[1]
else:
if not command:
command = line.rstrip("\n")
else:
output += line
dump_to_json(eventstream_file, timestamp, user, host, command, output)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('transcript_file', type=argparse.FileType('r', encoding="utf-8"))
parser.add_argument('eventstream_file', type=argparse.FileType('a'))
args = parser.parse_args()
main(args.transcript_file, args.eventstream_file)