Building a Python flow monitor with NetFlow and sFlow
Operational networks rarely need every packet retained, yet flow records reveal where traffic is going, how much is moving and when patterns change. A collector can turn this metadata into a practical view of bandwidth, service dependencies and suspicious behaviour without storing packet contents.
Creating a Python-based network flow monitor using NetFlow or sFlow data involves ingesting vendor exports, normalising them, retaining useful aggregates and presenting the results through dashboards or APIs. The key is to distinguish protocol facts from analytical assumptions, especially when exporters sample traffic or UDP delivery loses records.
Choosing between NetFlow and sFlow
NetFlow and sFlow provide different views of network activity. NetFlow exporters send flow summaries, while sFlow agents report sampled packets and interface counters. For a Python monitor, that distinction matters: sampled data can expose unusual destinations and protocol mixes, but counters and flow bytes are not equivalent observations.
Choose NetFlow when routers and switches already support it, particularly for accurate per-flow byte and packet totals. NetFlow v5 is simple, whereas v9 uses templates, sequence counters and richer fields such as IPv6, ASN data and VLAN identifiers. sFlow often suits high-speed campus or data-centre links because agents sample traffic and counters rather than track every conversation.
In Australia, a collector may see traffic to and from Sydney, Melbourne, Brisbane and regional offices, alongside endpoints in AWS ap-southeast-2 and Azure Australia East. Australian public addresses are allocated through APNIC, so retain origin ASN and country metadata when possible. Store timestamps in UTC; AEST and AEDT changes should never create gaps or duplicated hourly buckets.
Receiving and decoding exported data
Start with one collector built around asyncio and a datagram protocol, keeping network I/O separate from parsing. Bind configurable UDP ports, commonly 2055 or 4739 for NetFlow and 6343 for sFlow, and limit firewall access to known exporters where practical. Measure queue depth, parse failures, received bytes and socket drops; otherwise UDP loss can resemble a quiet network.
Decode binary formats with struct.unpack_from and typed dataclasses instead of ad hoc string splitting. NetFlow v9 needs a template cache keyed by exporter and template ID, including expiry and refresh handling. sFlow requires sample-type, agent-identifier and sampling-rate decoding. Normalise IPv4 and IPv6 with ipaddress, keep unknown fields explicit, and reject truncated datagrams without corrupting parser state.
Keep the protocol layer testable with sanitised packet captures and expected outputs. Test empty datagrams, malformed lengths, unknown templates, wrapped sequence counters and mixed versions. The collector should continue after a bad packet, while counters expose omissions that a successful exception handler could otherwise conceal.
Modelling records for useful analysis
Store a compact flow table, not raw packets. Useful fields include observation time, agent, ingress and egress interfaces, source and destination addresses, ports, protocol, bytes, packets, duration, sampling rate, VLAN and ASNs. Preserve interface direction because ingress and egress totals answer different questions. Keep timestamps in UTC and retain the original sampling rate beside each sampled observation.
SQLite suits a modest branch or prototype; PostgreSQL suits concurrent dashboards and longer retention. Daily rollups by source, destination, port, protocol and interface keep queries fast, while Parquet works for archival analysis. Set retention limits before detailed records become costly and index the fields most often used in filters.
Flow metadata can still expose personal information. An IP address may identify an individual or household even without payload, so apply the Australian Privacy Act where relevant and avoid retaining customer addresses longer than required. Restrict exports, log access and keep Australian datasets in approved local or cloud regions. ACSC guidance and the ASD Essential Eight offer useful baselines for collection hosts.
Practical checks for a reliable monitor
A reliable monitor needs checks at both ends of the pipeline. These compact lists separate collection correctness from analytical confidence.
Collection checks
- Confirm template refresh, sampling rates and exporter clock drift against expected values.
- Compare interface counters with flow totals; large gaps can indicate sampling or packet loss.
- Alert on sequence gaps, malformed datagrams, stale exporters and sustained socket-buffer drops.
- Test restoration with representative NetFlow and sFlow captures on every supported platform.
Analysis must account for how the data was produced, not merely what it contains.
Analysis checks
- Baseline ordinary hourly and weekday traffic before choosing alert thresholds.
- Rate alert volume by source, destination, port and ASN rather than raw flow count.
- Annotate NAT boundaries, VPN exits, cloud links and planned maintenance windows.
- Require corroborating evidence before treating a traffic spike as malicious.
Sampling and NAT can create convincing false anomalies. One sampled record does not prove a transfer, and an internal source may become an internet destination after translation. Put sampling rate, coverage gaps and data age beside every severity score so analysts can separate a real change from an incomplete feed.
Running and maintaining the monitor
Run the collector as an unprivileged service under systemd or a container platform. Separate configuration, secrets and writable data paths, restrict outbound access, and use a dedicated dashboard account with narrow permissions. Include health checks, version reporting and an upgrade procedure, and log configuration changes as carefully as code releases.
For an open-source release, publish the schema, supported protocol versions, licence and sample data, alongside a clear statement that the tool supplies indicators rather than attribution. The transparency expected in utilities such as DenyHosts, Kodos and Scratchy matters here: users should know what is measured, what is sampled and which assumptions can affect an alert.
A practical first deployment could cover an Australian university campus, a regional hospital network or a small cloud platform, then expand after operators compare the feed with router telemetry. Export Prometheus metrics for collector health and keep normalised flow counts in a separate analytics database. The result is a traceable network flow monitor that converts NetFlow or sFlow exports into evidence operators can inspect and act on confidently.
