Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Session 03 - Python for Forensics

The code here is to support the Session 03 lecture.

logParserExt.py

import sys, re

def usage():
    print("Illegal usage")
    print("python " + sys.argv[0] + " <logfile>")
    sys.exit()

if len(sys.argv) != 2:
    usage()

logfile = sys.argv[1]

print("[+] Processing: " + logfile)

totalCount = 0
ipAddresses = {}

logPattern = r'((\d{1,3}\.){3}\d{1,3}) '
f = open(logfile, 'r')
entries = f.readlines()
f.close()

protocolType = input("Enter the protocol type to filter (TCP, UDP, IRC, ICMP): ").upper()

filteredEntries = [entry.strip() for entry in entries if re.search(f'{protocolType}', entry, re.IGNORECASE)]

print("\nFiltered Entries for Protocol: ", protocolType)
print("=" * 30)
for entry in filteredEntries:
    print(entry)
print("=" * 30)

i = 0
while i != len(filteredEntries):
    if not re.search(r'^#', filteredEntries[i]):
        totalCount = totalCount + 1
        match = re.search(logPattern, filteredEntries[i])
        if match:
            ip = match.group(1)
            if ip in ipAddresses.keys():
                ipAddresses[ip] = ipAddresses[ip] + 1
            else:
                ipAddresses[ip] = 1
    i = i + 1

print("\nSummary Stats for Filtered Entries")
print("=" * 30)
print("Entries:\t\t\t" + str(totalCount))
print("Distinct IPs:\t\t\t" + str(len(ipAddresses.keys())))
print("=" * 30)
print("IP Count:\t")
for key in ipAddresses.keys():
    print(key, " ", ipAddresses[key])
print("=" * 30)
[ Last updated: Tuesday 28 October 2025 @ 22:16:52 +0000 // branch: master // commit: 5ebe398 ]