惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Vulnerabilities – Threatpost
aimingoo的专栏
aimingoo的专栏
B
Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
GbyAI
GbyAI
阮一峰的网络日志
阮一峰的网络日志
Engineering at Meta
Engineering at Meta
IT之家
IT之家
V
Visual Studio Blog
The Cloudflare Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
A
About on SuperTechFans
博客园 - 聂微东
Blog — PlanetScale
Blog — PlanetScale
N
News and Events Feed by Topic
A
Arctic Wolf
WordPress大学
WordPress大学
小众软件
小众软件
C
CERT Recently Published Vulnerability Notes
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
D
Darknet – Hacking Tools, Hacker News & Cyber Security
F
Fortinet All Blogs
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Y
Y Combinator Blog
T
Threat Research - Cisco Blogs
Latest news
Latest news
Simon Willison's Weblog
Simon Willison's Weblog
Cyberwarzone
Cyberwarzone
S
Schneier on Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
Lohrmann on Cybersecurity
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Privacy International News Feed
J
Java Code Geeks
Spread Privacy
Spread Privacy
宝玉的分享
宝玉的分享
I
Intezer
L
LangChain Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
G
GRAHAM CLULEY
博客园 - 叶小钗
博客园 - 三生石上(FineUI控件)
The GitHub Blog
The GitHub Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
News and Events Feed by Topic
AWS News Blog
AWS News Blog
Attack and Defense Labs
Attack and Defense Labs
Security Archives - TechRepublic
Security Archives - TechRepublic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Real-Time Network Telemetry for AI: Building an Asynchronous NetFlow/sFlow Ingestion Pipeline in Python
Alireza Razinejad · 2026-06-26 · via DEV Community

As AI architectures transition from static data processing to real-time agentic monitoring, the data engineering pipelines feeding them must adapt. If you are building an AI-driven anomaly detection model, a security agent, or an automated network observability tool, you can't rely on historical batch logs. You need live, structural telemetry straight from the network edge.

When monitoring network traffic at scale, two industry standards dominate: NetFlow (stateful conversation aggregation) and sFlow (stateless packet-level sampling).

In this post, we will build a production-grade, asynchronous network ingestion engine using Python and Scapy that captures live wireless traffic, extracts 5-tuple flow metrics, and streams structured JSON events ready to be swallowed by a message broker (like Kafka) or an AI vector database.


The Architectural Challenge: Avoid the Bottleneck

The biggest pitfall when writing a packet sniffer in Python is blocking the execution loop. If your script captures a packet, processes it, formats a JSON string, and logs it sequentially, your script will choke and drop thousands of packets during a sudden burst of network traffic.

To feed an AI infrastructure safely, we must decouple the Capture Phase from the Processing Phase using a Producer-Consumer multi-threaded pattern.

[ Wireless Adapter ] 
       │
       ▼ (Raw Packets)
┌────────────────────────────────────────────────────────┐
│ PHASE 1: Capture (Scapy AsyncSniffer Thread)          │
│ - Sniffs raw frames in a non-blocking background loop   │
└────────────────────────────────────────────────────────┘
       │
       ▼ (Fast Handoff: .put_nowait)
┌────────────────────────────────────────────────────────┐
│ PHASE 2: Buffer (Thread-Safe bounded Queue)           │
│ - Acts as a shock absorber for network traffic bursts  │
└────────────────────────────────────────────────────────┘
       │
       ▼ (Distributed to Worker Pool)
┌────────────────────────────────────────────────────────┐
│ PHASE 3: Process & Emit (Concurrent Thread Workers)    │
│ - Worker 1  │  Worker 2  │  Worker 3  │  Worker 4      │
│ - Decodes Layers (IP, TCP, UDP)                        │
│ - Updates Stateful NetFlow Cache (Aggregates)          │
│ - Outputs Structured JSON Streaming Event              │
└────────────────────────────────────────────────────────┘


Production-Grade Pipeline Implementation

Below is the complete, modern Python implementation utilizing Scapy's explicit layer APIs, asynchronous execution, and thread-safe buffering.

Prerequisites

Ensure you have the native packet capture library installed on your host system (libpcap for Linux/macOS, Npcap for Windows) and install Scapy:

pip install scapy

The Ingestion Code

import os
import sys
import queue
import time
import json
from dataclasses import dataclass, asdict
from concurrent.futures import ThreadPoolExecutor
from typing import Dict, Tuple, Optional

# Explicitly target specific submodules for deterministic enterprise scopes
from scapy.all import AsyncSniffer, Packet, conf
from scapy.layers.inet import IP, TCP, UDP

# --- CONFIGURATION ---
MAX_QUEUE_SIZE = 10000
NUM_WORKERS = 4
# Replace with your specific active network interface index or string name
INTERFACE: Optional[str | int] = 24  


# --- DATA MODELS ---
@dataclass(frozen=True)
class FlowKey:
    src_ip: str
    dst_ip: str
    src_port: int
    dst_port: int
    protocol: int


@dataclass
class FlowMetrics:
    packet_count: int = 0
    byte_count: int = 0
    first_seen: float = 0.0
    last_seen: float = 0.0


# --- INGESTION PIPELINE ENGINE ---
class AIStreamIngestionPipeline:
    def __init__(self, interface: Optional[str | int] = None):
        self.interface = interface
        self.packet_queue: queue.Queue[Packet] = queue.Queue(maxsize=MAX_QUEUE_SIZE)
        self.flow_cache: Dict[FlowKey, FlowMetrics] = {}
        self.executor = ThreadPoolExecutor(max_workers=NUM_WORKERS)
        self.is_running = False
        self.sniffer: Optional[AsyncSniffer] = None

    def _extract_packet_meta(self, packet: Packet) -> Optional[Tuple[FlowKey, int]]:
        """Parses raw layers using container-optimized syntax."""
        if IP not in packet:
            return None

        ip_layer = packet[IP]
        src_port, dst_port = 0, 0

        # Safe inspection of Layer 4 using direct class indexing
        if TCP in packet:
            src_port = packet[TCP].sport
            dst_port = packet[TCP].dport
        elif UDP in packet:
            src_port = packet[UDP].sport
            dst_port = packet[UDP].dport

        key = FlowKey(
            src_ip=ip_layer.src,
            dst_ip=ip_layer.dst,
            src_port=src_port,
            dst_port=dst_port,
            protocol=ip_layer.proto
        )
        return key, len(packet)

    def _worker_process_queue(self) -> None:
        """Isolated consumer thread pool extracting flow features."""
        while self.is_running or not self.packet_queue.empty():
            try:
                packet = self.packet_queue.get(timeout=0.5)
            except queue.Empty:
                continue

            meta = self._extract_packet_meta(packet)
            if not meta:
                self.packet_queue.task_done()
                continue

            key, packet_len = meta
            current_time = time.time()

            # 1. Stateful Aggregation (NetFlow Telemetry Layer)
            if key not in self.flow_cache:
                self.flow_cache[key] = FlowMetrics(first_seen=current_time)

            metrics = self.flow_cache[key]
            metrics.packet_count += 1
            metrics.byte_count += packet_len
            metrics.last_seen = current_time

            # 2. Structured Streaming Payload (sFlow Event Layer)
            ingest_payload = {
                "event_type": "network_flow_sample",
                "timestamp": current_time,
                "flow_key": asdict(key),
                "packet_size_bytes": packet_len,
                "aggregate_metrics": asdict(metrics)
            }

            # Emit clean JSON to stdout (pipe into a stream wrapper, Kafka, or vector db)
            print(json.dumps(ingest_payload))
            self.packet_queue.task_done()

    def _enqueue_packet(self, packet: Packet) -> None:
        """High-speed producer callback. Hands off raw socket frames immediately."""
        try:
            self.packet_queue.put_nowait(packet)
        except queue.Full:
            # Backpressure handling: Drops edge frames gracefully if queue overflows
            pass

    def start(self) -> None:
        """Spawns workers and executes the non-blocking packet sniffer thread."""
        print(f"[*] Initializing pipeline on interface: {self.interface or 'Default Active OS Interface'}",
              file=sys.stderr)
        self.is_running = True

        for _ in range(NUM_WORKERS):
            self.executor.submit(self._worker_process_queue)

        self.sniffer = AsyncSniffer(
            iface=self.interface,
            prn=self._enqueue_packet,
            store=False  # Crucial: Drops raw historical packets out of memory instantly
        )
        self.sniffer.start()
        print("[*] Ingestion pipeline is live and streaming...", file=sys.stderr)

    def stop(self) -> None:
        """Gracefully signs off threads and closes open sockets."""
        print("\n[*] Shutting down ingestion pipeline gracefully...", file=sys.stderr)
        if self.sniffer:
            self.sniffer.stop()

        self.is_running = False
        self.executor.shutdown(wait=True)
        print("[*] Pipeline stopped cleanly.", file=sys.stderr)


if __name__ == "__main__":
    # Administrative privilege guard for raw socket access
    if os.name != 'nt' and os.getuid() != 0:
        print("[-] Critical Error: Root privileges required for raw network socket access.", file=sys.stderr)
        sys.exit(1)

    # Windows Device GUID Resolution block
    target_interface = INTERFACE
    if os.name == 'nt' and isinstance(INTERFACE, int):
        try:
            target_interface = conf.ifaces.dev_from_index(INTERFACE)
            print(f"[*] Resolved index {INTERFACE} to device: {target_interface.description}", file=sys.stderr)
        except Exception as e:
            print(f"[-] Warning: Could not resolve interface index {INTERFACE}: {e}. Falling back.", file=sys.stderr)

    pipeline = AIStreamIngestionPipeline(interface=target_interface)
    try:
        pipeline.start()
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        pipeline.stop()


Under the Hood: Why This Architecture Works for AI

1. Modern Container Layer Membership

Instead of executing high-overhead inspection functions like packet.haslayer(IP), this script checks containment explicitly using IP in packet. Scapy overloads Python’s internal __contains__ magic methods, ensuring layer validation occurs at the compiler layer.

2. Zero-Memory Aggregation (store=False)

By default, Scapy stores every single packet captured in an internal history list inside RAM. Running a default sniffer on an enterprise pipeline for an hour will result in a quick memory leak crash. By assigning store=False in our AsyncSniffer, we consume the packet from the adapter, pass it to our local queue, and free its memory instantly.

3. Backpressure Protection via Bounded Queues

Our ingestion loop forces a strict maxsize=10000 rule and uses a non-blocking put_nowait() execution. If the downstream data processor (e.g., your LLM evaluator or vector engine) experiences a latency hiccup, the pipeline intentionally drops incoming packets at the edge rather than letting the memory buffer balloon out of control.

4. Machine-Readable Feature Matrix Output

The pipeline aggregates connection metadata into a stateful 5-tuple format, while instantly streaming stateless structural JSON tokens. This gives your downstream AI immediate access to critical parameters:

{
  "event_type": "network_flow_sample", 
  "timestamp": 1719409375.42, 
  "flow_key": {
    "src_ip": "10.17.245.72", 
    "dst_ip": "142.250.180.142", 
    "src_port": 54211, 
    "dst_port": 443, 
    "protocol": 6
  }, 
  "packet_size_bytes": 1420, 
  "aggregate_metrics": {
    "packet_count": 42, 
    "byte_count": 59640, 
    "first_seen": 1719409371.11, 
    "last_seen": 1719409375.42
  }
}

This structural metadata provides your AI system with a comprehensive macro-view map of network behavior, allowing agents to accurately cross-reference anomalies without drowning your entire feature store in costly, raw packet captures.