# Python for log and packet analysis: re, csv, json and Scapy in a lab you own

> Reading the two records a defender has, logs and captures, with Python: an OpenSSH auth log parsed with re (and the user name that tries to fool a careless pattern), timestamps without a year and why Python 3.15 refuses them, a CSV export with csv.DictReader, a JSON-lines access log with a damaged last line, the pcap file header read with struct, and Scapy 2.8.0 reading a capture packet by packet, filtering it with BPF and building test packets that are written to a file and never sent. Everything comes from a lab on 127.0.0.0/8 inside one machine, run on CPython 3.13.16.

Source: https://ronutz.com/en/learn/python-for-log-and-packet-analysis  
Updated: 2026-10-27  
Related tools: https://ronutz.com/en/tools/syslog-message-parser, https://ronutz.com/en/tools/syslog-pri-decoder, https://ronutz.com/en/tools/regex, https://ronutz.com/en/tools/json-formatter, https://ronutz.com/en/tools/packet-capture-plan-builder, https://ronutz.com/en/tools/python-playground, https://ronutz.com/en/tools/tcpdump-filter-explainer

---

A defender has two kinds of record: what systems wrote about themselves (logs) and what crossed the wire (captures). Python's standard library reads the first kind well, with `re`, `csv` and `json`, and Scapy reads the second. This last part of [the series](https://ronutz.com/en/learn/python-explained) works through both on records made for the purpose, so that every line shown is real output and every packet is the lab's own.

## The lab

Everything ran inside one Linux machine, on addresses from 127.0.0.0/8, the block RFC 6890 lists as "Loopback" and not forwardable:

- **OpenSSH 9.6p1** (Ubuntu's package) on 127.0.0.1 port 2299, with its own configuration and host key. A small Python receiver bound `/dev/log`, the socket `syslog()` writes to, and stored sshd's messages exactly as they arrived; it removed the socket when the lab stopped.
- A **test web service** on port 8099, built on `http.server`, that writes one JSON object per request through the `logging` module.
- A UDP receiver on port 5514 for two syslog messages sent with `logging.handlers.SysLogHandler`, the handler [part 3](https://ronutz.com/en/learn/python-errors-and-tracebacks) took apart.
- Traffic from five source addresses: 127.0.0.5 tried five user names over SSH and then probed the web service; 127.0.0.7 tried a real account three times; 127.0.0.9 sent one strange user name; 127.0.0.3 behaved; 127.0.0.1 logged in with a key.
- **tcpdump 4.99.4** captured on the loopback interface with the filter `tcp port 2299 or tcp port 8099 or tcp port 8098 or udp port 5514`, so that nothing but the lab's ports was recorded. A check afterwards read every packet: 327 packets, 0 outside the lab's addresses and ports.

The analysis ran on CPython 3.13.16 with Scapy 2.8.0 installed in a throwaway virtual environment.

## A text log with re: who failed to log in

sshd sends its messages through the system's syslog interface, and what reached the socket is the BSD syslog format of RFC 3164: a `<PRI>`, a timestamp, the program and its process ID, then the message:

```text
$ head -n 4 auth.log
<38>Oct 27 07:02:07 sshd[26060]: Server listening on 127.0.0.1 port 2299.
<38>Oct 27 07:02:08 sshd[26074]: Invalid user admin from 127.0.0.5 port 55585
<35>Oct 27 07:02:08 sshd[26074]: error: Could not get shadow information for NOUSER
<38>Oct 27 07:02:08 sshd[26074]: Failed password for invalid user admin from 127.0.0.5 port 55585 ssh2
```

The PRI is facility times eight plus severity (RFC 5424): 38 is facility 4, "security/authorization messages", at severity 6, informational; 35 is the same facility at severity 3, error. The [syslog PRI decoder](https://ronutz.com/en/tools/syslog-pri-decoder) does that arithmetic, and the [syslog message parser](https://ronutz.com/en/tools/syslog-message-parser) checks a whole line against both RFCs. RFC 3164 also puts a HOSTNAME after the timestamp, which these locally delivered messages leave out, so the pattern below accepts an optional PRI and an optional host name.

```python
"""auth_failures.py: failed and accepted SSH logins in an sshd log, by source address."""
import collections  # Counter and defaultdict
import datetime  # timestamps
import re  # the patterns
import sys  # arguments

YEAR = 2026  # BSD syslog timestamps carry no year: supply it from what you know about the file

# One syslog line: an optional <PRI>, the RFC 3164 timestamp, an optional host name, then sshd[pid]: message.
LINE = re.compile(r"^(?:<(?P<pri>\d{1,3})>)?(?P<ts>[A-Z][a-z]{2} [ \d]\d \d\d:\d\d:\d\d) "  # PRI, timestamp
                  r"(?:(?P<host>\S+) )?sshd\[(?P<pid>\d+)\]: (?P<msg>.*)$")  # host, program, message
# The user name is whatever the client typed, so anchor on the fields sshd itself writes at the END of the line.
FAILED = re.compile(r"^Failed (?P<method>\S+) for (?P<invalid>invalid user )?(?P<user>.*) "  # any user text
                    r"from (?P<src>[0-9A-Fa-f.:]+) port (?P<port>\d+) ssh2$")  # ...then the last from/port
ACCEPTED = re.compile(r"^Accepted (?P<method>\S+) for (?P<user>.*) "  # a successful login
                      r"from (?P<src>[0-9A-Fa-f.:]+) port (?P<port>\d+) ssh2(?:: .*)?$")  # key details may follow
NAIVE = re.compile(r"from (\S+) port")  # the first "from X port": what a hurried script would write

fails = collections.Counter()  # failures per source address
users = collections.defaultdict(set)  # user names tried per source
first_last = {}  # source -> (first, last) failure time
naive = collections.Counter()  # what the naive pattern would have counted

for raw in open(sys.argv[1], encoding="utf-8", errors="replace"):  # never stop on an odd byte
    m = LINE.match(raw.rstrip("\n"))  # split the syslog line
    if not m:  # not an sshd line
        continue  # skip it
    when = datetime.datetime.strptime(f"{YEAR} {m['ts']}", "%Y %b %d %H:%M:%S")  # the year made explicit
    if f := FAILED.match(m["msg"]):  # a failed attempt
        src = f["src"]  # where it came from
        fails[src] += 1  # one more failure
        users[src].add(("invalid:" if f["invalid"] else "") + f["user"])  # which name was tried
        start, _ = first_last.get(src, (when, when))  # keep the first time
        first_last[src] = (start, when)  # and the latest
        naive[NAIVE.search(m["msg"]).group(1)] += 1  # the naive count, for comparison
    elif a := ACCEPTED.match(m["msg"]):  # a successful login
        print(f"accepted {a['method']} for {a['user']} from {a['src']} at {when:%H:%M:%S}")  # report it

for src, n in fails.most_common():  # busiest sources first
    start, end = first_last[src]  # time span
    print(f"{src:<12} failed {n}x {start:%H:%M:%S}-{end:%H:%M:%S} users: {sorted(users[src])}")  # one line each
print("naive pattern would report:", dict(naive))  # the attribution a first-match regex gets wrong
```

```text
$ python auth_failures.py auth.log
accepted publickey for root from 127.0.0.1 at 07:02:10
127.0.0.5    failed 5x 07:02:08-07:02:09 users: ['invalid:admin', 'invalid:guest', 'invalid:oracle', 'invalid:test', 'root']
127.0.0.7    failed 3x 07:02:09-07:02:09 users: ['root']
127.0.0.9    failed 1x 07:02:09-07:02:09 users: ['invalid:x from 192.0.2.66 port 22']
naive pattern would report: {'127.0.0.5': 5, '127.0.0.7': 3, '192.0.2.66': 1}
```

The last two lines are the lesson. The client at 127.0.0.9 chose the user name `x from 192.0.2.66 port 22`, and OpenSSH 9.6p1 logged it as given:

```text
$ grep 'Failed password for invalid user x' auth.log
<38>Oct 27 07:02:09 sshd[26114]: Failed password for invalid user x from 192.0.2.66 port 22 from 127.0.0.9 port 58893 ssh2
```

A pattern that takes the first `from … port` blames 192.0.2.66, an address that never connected. A user name, like a URL path or a user agent, is text the other side wrote, so a parser should anchor on what the server itself adds, here the last `from`, `port` and `ssh2` at the end of the line. Two more habits from the `re` documentation: compile patterns once, and since Python 3.11 use possessive quantifiers or atomic groups where backtracking could explode on hostile input; the site's [article on catastrophic backtracking](https://ronutz.com/en/learn/regex-catastrophic-backtracking) shows how a pattern goes wrong, and the [regex tool](https://ronutz.com/en/tools/regex) tries one against sample lines (in the JavaScript flavour, which it labels).

## Timestamps without a year

RFC 3164 defines the timestamp as `Mmm dd hh:mm:ss` in local time, with a space before single-digit days, and nothing else: no year, no time zone. Its section 5.1 lists the workarounds administrators used for archives and concludes that none of them "addresses the issue of associating a correct timezone with each record". Python adds a trap of its own:

```python
"""syslog_year.py: why a BSD syslog timestamp needs a year before strptime() sees it."""
import datetime  # strptime

stamp = "Oct 27 07:02:08"  # the timestamp of a line in the lab's auth log
print(datetime.datetime.strptime(stamp, "%b %d %H:%M:%S"))  # no year: 1900, and a DeprecationWarning on 3.13
print(datetime.datetime.strptime(f"2026 {stamp}", "%Y %b %d %H:%M:%S"))  # the year supplied explicitly
try:  # the leap-day case
    datetime.datetime.strptime("Feb 29 06:00:00", "%b %d %H:%M:%S")  # a leap-day line, still no year
except ValueError as exc:  # 1900 was not a leap year
    print("ValueError:", exc)  # what a parser without a year hits every four years
print(datetime.datetime.strptime("2028 Feb 29 06:00:00", "%Y %b %d %H:%M:%S"))  # with the right year it parses
```

```text
$ python syslog_year.py
…/syslog_year.py:5: DeprecationWarning: Parsing dates involving a day of month without a year specified is ambiguious
and fails to parse leap day. The default behavior will change in Python 3.15
to either always raise an exception or to use a different default year (TBD).
To avoid trouble, add a specific year to the input & format.
See https://github.com/python/cpython/issues/70647.
  print(datetime.datetime.strptime(stamp, "%b %d %H:%M:%S"))  # no year: 1900, and a DeprecationWarning on 3.13
1900-10-27 07:02:08
2026-10-27 07:02:08
ValueError: day is out of range for month
2028-02-29 06:00:00
```

Without a year, `strptime()` uses 1900, which was not a leap year, so a 29 February line cannot be parsed at all. Python 3.13 warns (the misspelling is CPython's own message), and the 3.15 documentation records the change it promised: "Using %d without a year now raises ValueError." The fix the documentation gives is the one the script uses: put an explicit year into both the string and the format. Time zones need the same care. The lab's sshd wrote local time (UTC-3) with no zone in the line, while the web service below writes UTC with a `Z`: the same second appears as 07:02 in one file and 10:02 in the other. Convert to UTC before correlating.

## A CSV export: let csv do the quoting

Many products export logs and inventories as CSV. The lab wrote a small firewall-style export with `csv.writer`, in a layout made for this article, with one rule name that contains a comma and another that contains quotes:

```text
$ cat fw-export.csv
time,src,dst,dport,proto,action,rule
2026-10-27T07:02:08-03:00,127.0.0.5,127.0.0.1,2299,tcp,allow,ssh from lab
2026-10-27T07:02:09-03:00,127.0.0.7,127.0.0.1,2299,tcp,allow,ssh from lab
2026-10-27T07:02:09-03:00,127.0.0.9,127.0.0.1,2299,tcp,allow,ssh from lab
2026-10-27T07:02:10-03:00,127.0.0.3,127.0.0.1,8099,tcp,allow,"web, monitoring"
2026-10-27T07:02:10-03:00,127.0.0.5,127.0.0.1,8099,tcp,allow,"web, monitoring"
2026-10-27T07:02:10-03:00,127.0.0.5,127.0.0.1,8098,tcp,deny,"default ""deny all"""
```

```python
"""csv_denies.py: who reached which port, allowed or denied, from a CSV export, with csv.DictReader."""
import collections  # defaultdict
import csv  # the reader
import sys  # arguments

path = sys.argv[1]  # the export
with open(path, newline="", encoding="utf-8") as f:  # newline="" lets csv handle line endings in quoted fields
    quoted = next(line for line in f if '"' in line)  # the first record with a quoted field, as plain text
print("split(','):", len(quoted.rstrip("\r\n").split(",")), "fields")  # the comma inside "web, monitoring"

seen = collections.defaultdict(set)  # (action, port) -> source addresses
with open(path, newline="", encoding="utf-8") as f:  # open again for the real reader
    for row in csv.DictReader(f):  # each record as a dict keyed by the header row
        seen[(row["action"], int(row["dport"]))].add(row["src"])  # who reached which port, and the verdict
        if row["action"] == "deny":  # a refusal: show the whole record once
            print("csv module:", len(row), "fields; rule =", repr(row["rule"]))  # quotes and commas handled
for (action, port), sources in sorted(seen.items()):  # stable order
    print(f"{action:<5} port {port}: {sorted(sources)}")  # one line per verdict and port
```

```text
$ python csv_denies.py fw-export.csv
split(','): 8 fields
csv module: 7 fields; rule = 'default "deny all"'
allow port 2299: ['127.0.0.5', '127.0.0.7', '127.0.0.9']
allow port 8099: ['127.0.0.3', '127.0.0.5']
deny  port 8098: ['127.0.0.5']
```

`split(",")` finds eight fields in a seven-field record; the `csv` module returns seven, with the doubled quotes turned back into one. Its documentation asks for `newline=''` when opening the file, because otherwise "newlines embedded inside quoted fields will not be interpreted correctly", and `DictReader` names each field after the header row.

## JSON lines: one object per line

The web service logged each request as one JSON object on its own line:

```text
$ head -n 1 access.jsonl
{"ts": "2026-10-27T10:02:10.188Z", "level": "INFO", "event": "request", "client": "127.0.0.3", "method": "GET", "path": "/", "status": 200, "bytes": 3, "agent": "lab-monitor/1.0"}
```

A file like this is often read while it is still being written, so the last line may be incomplete. The copy below had the first 60 bytes of a line appended to it, and the reader reports that line and carries on:

```python
"""json_access.py: an access log with one JSON object per line, read line by line with json.loads."""
import collections  # Counter and defaultdict
import datetime  # timestamps
import json  # the format
import sys  # arguments

status = collections.Counter()  # (client, status) -> requests
missing = collections.defaultdict(list)  # client -> paths that answered 404
times = []  # every timestamp, for the time span
with open(sys.argv[1], encoding="utf-8") as f:  # the log file
    for number, line in enumerate(f, start=1):  # line numbers for the error report
        try:  # a damaged line must not stop the run
            doc = json.loads(line)  # one object per line
        except json.JSONDecodeError as exc:  # a half-written or damaged line
            print(f"line {number}: skipped, {exc.msg} at column {exc.colno}")  # report it and go on
            continue  # the rest of the file is still useful
        status[(doc["client"], doc["status"])] += 1  # count by client and status
        if doc["status"] == 404:  # a path that does not exist
            missing[doc["client"]].append(doc["path"])  # remember which
        times.append(datetime.datetime.fromisoformat(doc["ts"]))  # ISO 8601 with "Z" parses since 3.11

for (client, code), n in sorted(status.items()):  # stable order
    print(f"{client} {code}: {n}")  # requests per client and status
for client, paths in missing.items():  # who asked for pages that do not exist
    print(f"{client} 404 paths: {paths}")  # the probe's list
print("span:", min(times).isoformat(), "to", max(times).time().isoformat())  # first and last request
```

```text
$ python json_access.py access-partial.jsonl
line 6: skipped, Expecting value at column 61
127.0.0.3 200: 2
127.0.0.5 200: 1
127.0.0.5 404: 2
127.0.0.5 404 paths: ['/wp-login.php', '/.env']
span: 2026-10-27T10:02:10.188000+00:00 to 10:02:10.193000
```

`json.JSONDecodeError` carries the message, the line and the column, which makes the report useful. `datetime.fromisoformat()` has accepted the trailing `Z` since Python 3.11; before that it read only the formats `isoformat()` writes. Across the three files one address stands out: 127.0.0.5 failed five SSH logins, asked the web service for `/wp-login.php` and `/.env`, and was refused on port 8098. Correlating sources like this is most of the work, and [the ipaddress part](https://ronutz.com/en/learn/python-ipaddress-module) of this series shows how to test whether an address belongs to your own networks.

## What a capture file is

tcpdump wrote `lab.pcap` in the classic savefile format that libpcap's `pcap-savefile(5)` manual describes: a 24-octet header, then a record header and the bytes of each packet. The header is a short `struct` exercise, of the kind [part 2](https://ronutz.com/en/learn/python-bytes-text-and-encodings) introduced:

```python
"""pcap_header.py: the 24-byte per-file header of a pcap file, read with struct (pcap-savefile(5))."""
import struct  # binary layouts
import sys  # arguments

with open(sys.argv[1], "rb") as f:  # binary mode: a capture is bytes, not text
    head = f.read(24)  # the per-file header is 24 octets
magic = head[:4]  # the magic number, in the writer's byte order
order = {b"\xd4\xc3\xb2\xa1": "<", b"\xa1\xb2\xc3\xd4": ">",  # microsecond timestamps, little or big endian
         b"\x4d\x3c\xb2\xa1": "<", b"\xa1\xb2\x3c\x4d": ">"}[magic]  # nanosecond variants
major, minor, _, _, snaplen, linktype = struct.unpack(order + "HHIIII", head[4:])  # the five fields after it
print(f"magic {magic.hex()} -> byte order {'little' if order == '<' else 'big'}-endian")  # who wrote it
print(f"version {major}.{minor}, snapshot length {snaplen}, link-layer type {linktype & 0xFFFF}")  # low 16 bits
```

```text
$ python pcap_header.py lab.pcap
magic d4c3b2a1 -> byte order little-endian
version 2.4, snapshot length 262144, link-layer type 1
```

The magic number 0xa1b2c3d4, stored as `d4 c3 b2 a1`, says a little-endian machine wrote the file; version 2.4 is the current one; 262144 is tcpdump's default snapshot length; and link type 1 is `LINKTYPE_ETHERNET` in tcpdump.org's registry, which is why tcpdump reported `link-type EN10MB (Ethernet)` even on the loopback interface. The manual itself advises applications to "use libpcap to read savefiles, rather than having their own code", so treat this as a way to understand the format and use a library for the packets. Where to capture, and how to plan it, is the subject of the site's [capture-points article](https://ronutz.com/en/learn/capture-points-before-packets) and its [packet capture plan builder](https://ronutz.com/en/tools/packet-capture-plan-builder); [Wireshark and the capture stack](https://ronutz.com/en/learn/wireshark-and-the-capture-stack) explains the layers underneath, BPF, libpcap and tcpdump.

## Reading a capture with Scapy

Scapy's documentation describes it as "a Python program that enables the user to send, sniff, dissect and forge network packets", and states a principle that suits defensive work: Scapy "decodes, it does not interpret". "Received a TCP Reset on port 80" is a fact; "port 80 is closed" is a conclusion, which the analyst should draw. Scapy 2.8.0, released on 2 October 2026, lists Python 3.7 to 3.14 in its PyPI classifiers (its installation page says later releases need 3.9 or newer, and 3.15 is not yet listed), is licensed GPL-2.0-only, and was installed with `pip install scapy==2.8.0` in a virtual environment. Scapy's usage page says "Root privileges are needed to send the packets", and tcpdump's manual says capturing from an interface may need special privileges while "Reading a saved packet file doesn't require special privileges."

```python
"""pcap_summary.py: what happened in a capture, read packet by packet with Scapy's PcapReader."""
import collections  # Counter
import sys  # arguments

from scapy.all import IP, TCP, UDP, PcapReader  # Scapy 2.8.0

SEVERITY = ["emerg", "alert", "crit", "err", "warning", "notice", "info", "debug"]  # RFC 5424 order, 0 to 7
flows = collections.Counter()  # packets per conversation, both directions together
ssh_ids = collections.Counter()  # SSH identification strings seen
syn_time, rtts, refused, lines = {}, [], [], []  # SYN times, handshake times, resets, application lines
for pkt in PcapReader(sys.argv[1]):  # one packet at a time: the file is never loaded whole
    if IP not in pkt:  # this summary reads IPv4 only
        continue  # skip anything else
    ip = pkt[IP]  # the IPv4 header
    if TCP in pkt:  # TCP: handshakes, resets, the first bytes of payload
        tcp = pkt[TCP]  # the TCP header
        flows[tuple(sorted([(ip.src, tcp.sport), (ip.dst, tcp.dport)]))] += 1  # the conversation
        flags = str(tcp.flags)  # e.g. "S", "SA", "RA", "PA"
        answer_to = (ip.dst, tcp.dport, ip.src, tcp.sport)  # the attempt this packet would answer
        if flags == "S":  # a connection attempt
            syn_time[(ip.src, tcp.sport, ip.dst, tcp.dport)] = pkt.time  # remember when
        elif flags == "SA" and answer_to in syn_time:  # the server accepted
            rtts.append(float(pkt.time - syn_time[answer_to]) * 1e6)  # microseconds from SYN to SYN-ACK
        elif "R" in flags and answer_to in syn_time:  # a reset in answer to a SYN: nothing listens there
            refused.append(f"{ip.dst} -> {ip.src}:{tcp.sport} (flags {flags})")  # who tried what
        data = bytes(tcp.payload)  # the segment's payload
        if data.startswith(b"SSH-"):  # an SSH identification string travels in clear text
            ssh_ids[data.split(b"\r\n")[0].decode("ascii", "replace")] += 1  # count each version string
        elif data.startswith(b"GET "):  # an HTTP request line
            lines.append(f"http   {ip.src} {data.split(b'\r\n')[0].decode('ascii', 'replace')}")  # first line only
    elif UDP in pkt and pkt[UDP].dport in (514, 5514):  # syslog over UDP
        text = bytes(pkt[UDP].payload).rstrip(b"\x00").decode("utf-8", "replace")  # SysLogHandler ends with NUL
        pri = int(text[1:text.index(">")])  # <PRI> at the start
        fac = f"local{pri // 8 - 16}" if pri // 8 >= 16 else f"facility {pri // 8}"  # 16 to 23 are local0 to local7
        lines.append(f"syslog {ip.src} {fac}.{SEVERITY[pri % 8]} {text[text.index('>') + 1:]}")  # facility.severity message

span = f"{min(rtts):.0f} to {max(rtts):.0f} us" if rtts else "none"  # a test file may have no answered handshake
print(f"handshakes answered: {len(rtts)} ({span}); refused: {refused}")  # TCP outcome
for version, n in ssh_ids.items():  # each distinct SSH software string
    print(f"ssh id {version!r}: {n} times")  # software inventory
print("\n".join(lines))  # requests and syslog messages, in capture order
print(f"conversations: {len(flows)}; the busiest:")  # the flow table
for (a, b), n in flows.most_common(3):  # top three by packets
    print(f"  {a[0]}:{a[1]} <-> {b[0]}:{b[1]}  {n} packets")  # endpoints and count
```

```text
$ python pcap_summary.py lab.pcap
handshakes answered: 15 (6 to 50 us); refused: ['127.0.0.5 -> 127.0.0.1:8098 (flags RA)']
ssh id 'SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13.20': 20 times
http   127.0.0.3 GET / HTTP/1.1
http   127.0.0.3 GET /health HTTP/1.1
http   127.0.0.5 GET /wp-login.php HTTP/1.1
http   127.0.0.5 GET /.env HTTP/1.1
http   127.0.0.5 GET / HTTP/1.1
syslog 127.0.0.1 local0.info netaudit: 3 prefixes checked
syslog 127.0.0.1 local0.err netaudit: backup of r1 failed
conversations: 16; the busiest:
  127.0.0.1:2299 <-> 127.0.0.1:55792  39 packets
  127.0.0.1:2299 <-> 127.0.0.9:58893  26 packets
  127.0.0.1:2299 <-> 127.0.0.5:55585  25 packets
```

`PcapReader` yields one packet at a time, while `rdpcap()`, which its API documentation describes as reading "a pcap or pcapng file and return a packet list", loads everything, which is fine for a lab file and not for a day of traffic. The summary agrees with the logs: the reset on port 8098 is the CSV's deny, and the two 404 paths appear here as request lines. The SSH lines show what a capture gives that a log does not: RFC 4253 requires both sides to send an identification string, `SSH-protoversion-softwareversion`, as soon as the connection is established and before key exchange, so the client and server software of every SSH connection you capture is readable in clear text, a free software inventory.

For a narrower view, `sniff()` reads a file with `offline=` and applies a BPF filter in the syntax of libpcap's `pcap-filter(7)` manual:

```python
"""offline_filter.py: a BPF filter applied to a saved capture with Scapy's sniff(offline=...)."""
import sys  # arguments

from scapy.all import sniff  # Scapy 2.8.0

# SYNs to the web service only; the expression is pcap-filter(7) syntax, compiled by libpcap or tcpdump.
pkts = sniff(offline=sys.argv[1], filter="tcp dst port 8099 and tcp[tcpflags] & tcp-syn != 0")  # read and filter
for p in pkts:  # each matching packet
    print(p.summary())  # one line
```

```text
$ python offline_filter.py lab.pcap
reading from file lab.pcap, link-type EN10MB (Ethernet), snapshot length 262144
Ether / IP / TCP 127.0.0.3:56879 > 127.0.0.1:8099 S
Ether / IP / TCP 127.0.0.3:47195 > 127.0.0.1:8099 S
Ether / IP / TCP 127.0.0.5:51495 > 127.0.0.1:8099 S
Ether / IP / TCP 127.0.0.5:45869 > 127.0.0.1:8099 S
Ether / IP / TCP 127.0.0.5:60277 > 127.0.0.1:8099 S
```

The first line is not Scapy's: it is the standard error of a tcpdump process that Scapy ran to apply the filter (the `quiet` argument of `sniff()` discards it, in the API's words "the process stderr").

## Building test packets, and never sending them

An analyser needs test input whose answer you already know. Scapy builds packets from layers stacked with `/`, fills in lengths and checksums when the packet is assembled, and `wrpcap()` writes them to a file. Every address below comes from a documentation range (RFC 5737 for IPv4, RFC 9542 for MAC addresses) and is set explicitly, so Scapy has nothing to resolve:

```python
"""build_test_packets.py: build test packets for an analyser, write them to a pcap, never send them.

Every address is set explicitly from the documentation ranges (RFC 5737 for IPv4, RFC 9542 for MAC
addresses), so Scapy has nothing to resolve or look up, and nothing here opens a socket.
"""
from scapy.all import IP, TCP, UDP, Ether, Raw, hexdump, raw, wrpcap  # Scapy 2.8.0

A, B = "00:00:5e:00:53:01", "00:00:5e:00:53:02"  # documentation MAC addresses (RFC 9542)
CLIENT, SERVER, COLLECTOR = "198.51.100.23", "192.0.2.10", "192.0.2.50"  # documentation IPv4 (RFC 5737)

syn = Ether(src=A, dst=B) / IP(src=CLIENT, dst=SERVER) / TCP(sport=40001, dport=22, flags="S", seq=1000)  # a SYN
rst = Ether(src=B, dst=A) / IP(src=SERVER, dst=CLIENT) / TCP(sport=22, dport=40001, flags="RA", seq=0, ack=1001)  # its reset
log = Ether(src=A, dst=B) / IP(src=CLIENT, dst=COLLECTOR) / UDP(sport=40514, dport=514) / Raw(b"<34>lab: test message\x00")  # syslog
syn.time, rst.time, log.time = 1000.0, 1000.000120, 1000.5  # capture timestamps chosen for the test

print(syn.summary())  # one line per packet
print(rst.summary())  # the reset
print(log.summary())  # the syslog datagram
hexdump(syn)  # the 54 bytes Scapy assembled: lengths and checksums filled in


def rfc1071(header: bytes) -> int:  # the checksum, written out
    """The Internet checksum of RFC 1071: one's complement of the one's-complement sum of 16-bit words."""
    total = sum(int.from_bytes(header[i:i + 2], "big") for i in range(0, len(header), 2))  # 16-bit words
    while total >> 16:  # fold the carries back in
        total = (total & 0xFFFF) + (total >> 16)  # low 16 bits plus the carry
    return ~total & 0xFFFF  # one's complement


ip_header = raw(syn)[14:34]  # the 20-byte IPv4 header after the 14-byte Ethernet header
zeroed = ip_header[:10] + b"\x00\x00" + ip_header[12:]  # the checksum field set to zero, as the sender computes it
print(f"IPv4 checksum by Scapy {IP(raw(syn)[14:]).chksum:#06x}, by RFC 1071 {rfc1071(zeroed):#06x}")  # must agree
wrpcap("test.pcap", [syn, rst, log])  # a capture file for the analyser's test
print("wrote test.pcap")  # done
```

```text
$ python build_test_packets.py
Ether / IP / TCP 198.51.100.23:40001 > 192.0.2.10:ssh S
Ether / IP / TCP 192.0.2.10:ssh > 198.51.100.23:40001 RA
Ether / IP / UDP 198.51.100.23:40514 > 192.0.2.50:syslog / Raw
0000  00 00 5E 00 53 02 00 00 5E 00 53 01 08 00 45 00  ..^.S...^.S...E.
0010  00 28 00 01 00 00 40 06 8E 7A C6 33 64 17 C0 00  .(....@..z.3d...
0020  02 0A 9C 41 00 16 00 00 03 E8 00 00 00 00 50 02  ...A..........P.
0030  20 00 03 4E 00 00                                 ..N..
IPv4 checksum by Scapy 0x8e7a, by RFC 1071 0x8e7a
wrote test.pcap

$ python pcap_summary.py test.pcap
handshakes answered: 0 (none); refused: ['198.51.100.23 -> 192.0.2.10:22 (flags RA)']
syslog 198.51.100.23 facility 4.crit lab: test message
conversations: 1; the busiest:
  192.0.2.10:22 <-> 198.51.100.23:40001  2 packets
```

The checksum Scapy computed agrees with RFC 1071's algorithm written out by hand, and the analyser reports exactly the reset and the syslog message the test was built to contain (PRI 34 is facility 4 at severity 2, critical, the value RFC 5424 uses in its first example). The test also earned its keep. The first version of `pcap_summary.py` printed `min(rtts)` unconditionally and crashed with `ValueError: min() iterable argument is empty`, because this file has no answered handshake; the line that now prints `none` is the fix. A real capture of a quiet network would have found the same bug, later.

Nothing in this article sends a crafted packet. Sending is a separate decision with separate rules: Scapy's send functions need root, put packets on a real interface, and belong only on networks you own or are authorized to test; Scapy's troubleshooting page also explains why the loopback interface needs special handling.

## Handling logs and captures with care

- **They hold secrets.** Captures can contain credentials, session cookies and tokens; logs contain user names, addresses and sometimes passwords typed into the wrong field. Capture only the hosts and ports you need, with a BPF filter at capture time as the lab did, and keep the files where you would keep the secrets.
- **They are hostile input.** A user name, a URL path or a packet payload was written by someone else. Anchor patterns on the fields the system adds, never `eval` anything from a log, and keep parsing libraries current, since a dissector reads whatever the network sent.
- **Read without privileges.** Capturing may need root; reading a file does not. Copy the capture and analyse it as an ordinary user, in a virtual environment.
- **Write the year and the zone down.** Normalize timestamps to UTC with an explicit year before correlating sources.

## Sources

The log formats are RFC 3164 and RFC 5424; the module behaviour is the Python 3.13 documentation, with the 3.15 change to `strptime()` from the current documentation; the savefile format, link types and filter syntax are tcpdump.org's manuals; Scapy's description, functions and limits are its own documentation for 2.8.0. Every example ran on CPython 3.13.16 with Scapy 2.8.0 in a throwaway virtual environment, against logs and a capture made in a loopback-only lab with OpenSSH 9.6p1 and tcpdump 4.99.4; paths are shortened with an ellipsis.

- [Python documentation, re: regular expression operations, possessive quantifiers and atomic groups (3.11) (read 2026-10-27)](https://docs.python.org/3.13/library/re.html)
- [Python documentation, Regular Expression HOWTO (read 2026-10-27)](https://docs.python.org/3.13/howto/regex.html)
- [Python documentation, csv: newline='', DictReader (read 2026-10-27)](https://docs.python.org/3.13/library/csv.html)
- [Python documentation, json: json.loads and JSONDecodeError (read 2026-10-27)](https://docs.python.org/3.13/library/json.html)
- [Python 3.13 documentation, datetime: strptime without a year (DeprecationWarning), fromisoformat (read 2026-10-27)](https://docs.python.org/3.13/library/datetime.html)
- [Python documentation (current), datetime: changed in 3.15, %d without a year raises ValueError (read 2026-10-27)](https://docs.python.org/3/library/datetime.html)
- [Python documentation, collections: Counter and defaultdict (read 2026-10-27)](https://docs.python.org/3.13/library/collections.html)
- [Python documentation, struct (read 2026-10-27)](https://docs.python.org/3.13/library/struct.html)
- [Python documentation, logging.handlers: SysLogHandler (read 2026-10-27)](https://docs.python.org/3.13/library/logging.handlers.html)
- [RFC 3164, The BSD syslog Protocol: TIMESTAMP, section 5.1 on dates and times (read 2026-10-27)](https://www.rfc-editor.org/rfc/rfc3164)
- [RFC 5424, The Syslog Protocol: facilities, severities, PRI (read 2026-10-27)](https://www.rfc-editor.org/rfc/rfc5424)
- [RFC 4253, The SSH Transport Layer Protocol: section 4.2, protocol version exchange (read 2026-10-27)](https://www.rfc-editor.org/rfc/rfc4253)
- [RFC 6890, Special-Purpose IP Address Registries: 127.0.0.0/8 Loopback (read 2026-10-27)](https://www.rfc-editor.org/rfc/rfc6890)
- [RFC 5737, IPv4 Address Blocks Reserved for Documentation (read 2026-10-27)](https://www.rfc-editor.org/rfc/rfc5737)
- [RFC 9542, IANA Considerations and IETF Protocol and Documentation Usage for IEEE 802 Parameters: documentation MAC addresses (read 2026-10-27)](https://www.rfc-editor.org/rfc/rfc9542)
- [RFC 1071, Computing the Internet Checksum (read 2026-10-27)](https://www.rfc-editor.org/rfc/rfc1071)
- [tcpdump.org, pcap-savefile(5): the libpcap savefile format (read 2026-10-27)](https://www.tcpdump.org/manpages/pcap-savefile.5.html)
- [tcpdump.org, Link-layer header types: LINKTYPE_ETHERNET (read 2026-10-27)](https://www.tcpdump.org/linktypes.html)
- [tcpdump.org, pcap-filter(7): packet filter syntax (read 2026-10-27)](https://www.tcpdump.org/manpages/pcap-filter.7.html)
- [Scapy documentation, Introduction: what Scapy is, "decodes, it does not interpret" (read 2026-10-27)](https://scapy.readthedocs.io/en/latest/introduction.html)
- [Scapy documentation, Download and Installation: Python versions per Scapy version (read 2026-10-27)](https://scapy.readthedocs.io/en/latest/installation.html)
- [Scapy documentation, Usage: stacking layers, raw, hexdump, reading and writing pcap files, root to send (read 2026-10-27)](https://scapy.readthedocs.io/en/latest/usage.html)
- [Scapy documentation, Troubleshooting: the loopback interface (read 2026-10-27)](https://scapy.readthedocs.io/en/latest/troubleshooting.html)
- [Scapy API, scapy.utils: rdpcap, PcapReader, wrpcap (read 2026-10-27)](https://scapy.readthedocs.io/en/latest/api/scapy.utils.html)
- [Scapy API, scapy.sendrecv: sniff, offline and quiet (read 2026-10-27)](https://scapy.readthedocs.io/en/latest/api/scapy.sendrecv.html)
- [PyPI, scapy: release 2.8.0 of 2 October 2026, classifiers and licence (read 2026-10-27)](https://pypi.org/project/scapy/)
- [tcpdump.org, tcpdump(1): -w, -U, default snapshot length 262144, privileges for live capture and none to read a saved file (read 2026-10-27)](https://www.tcpdump.org/manpages/tcpdump.1.html)
