Skip to main content
The python command provides an interactive Python shell or executes Python scripts with Retis events automatically imported.

Usage

retis python [SCRIPT] [ARGS...] [OPTIONS]

Overview

The python command enables custom event analysis using Python. You can either drop into an interactive shell for exploration or execute scripts for automated processing.

Arguments

SCRIPT
path
Python script to execute.Can be:
  • Full path to a .py file
  • Script name (without .py) from standard locations
  • Omitted to start an interactive shell
Standard script locations:
  • $HOME/.config/retis/python/
  • /usr/share/retis/python/
retis python analysis.py
retis python analysis  # Searches standard locations
retis python  # Interactive shell
ARGS
string
Arguments for the Python script.Available in the script as sys.argv.
retis python script.py arg1 arg2 --flag

Options

--input
path
default:"retis.data"
File from which to read events.
retis python --input events.data script.py
retis python -i capture.data

Examples

# Start Python shell with events loaded
retis python

Python API

In Python scripts or the interactive shell, Retis events are automatically available:
#!/usr/bin/env python3
# Events are pre-loaded and available

for event in events:
    if event.packet:
        print(f"Packet from {event.kernel.symbol}")
        print(f"  Length: {event.packet.len}")
        print(f"  Data: {event.packet.data[:20]}...")  # First 20 bytes

Event Object Structure

Events have the following sections (when available):
event.common        # Common metadata (timestamp, task, etc.)
event.kernel        # Kernel probe information
event.packet        # Raw packet data
event.skb           # Socket buffer metadata
event.skb_tracking  # Tracking information
event.ct            # Conntrack data
event.dev           # Network device info
event.netns         # Namespace information
event.ovs           # OpenVSwitch data
event.nft           # Nftables data

Script Examples

Count packets by probe

#!/usr/bin/env python3
from collections import Counter

probes = Counter()

for event in events:
    if event.kernel:
        probe = f"{event.kernel.probe_type}:{event.kernel.symbol}"
        probes[probe] += 1

for probe, count in probes.most_common():
    print(f"{probe}: {count}")

Extract packet data

#!/usr/bin/env python3
import sys

for event in events:
    if event.packet and event.packet.len > 0:
        # Process packet bytes
        data = event.packet.data
        # Write to file, parse headers, etc.
        print(f"Packet length: {event.packet.len}")

Filter by criteria

#!/usr/bin/env python3

# Find all dropped packets
drops = [e for e in events if hasattr(e, 'skb_drop')]
print(f"Found {len(drops)} dropped packets")

for event in drops:
    print(f"  Drop reason: {event.skb_drop.drop_reason}")
    if event.kernel:
        print(f"  At: {event.kernel.symbol}")

Timestamp analysis

#!/usr/bin/env python3

if len(events) < 2:
    print("Need at least 2 events")
    sys.exit(1)

timestamps = [e.common.timestamp for e in events if e.common]

start = min(timestamps)
end = max(timestamps)
duration = end - start

print(f"Capture duration: {duration} ns ({duration / 1e9:.2f} s)")
print(f"Total events: {len(events)}")
print(f"Events per second: {len(events) / (duration / 1e9):.2f}")

Interactive Shell

Start an interactive Python shell:
retis python
Example session:
>>> # Events are already loaded
>>> len(events)
1523

>>> # Inspect first event
>>> event = events[0]
>>> event.kernel.symbol
'netif_receive_skb'

>>> # Filter events
>>> drops = [e for e in events if hasattr(e, 'skb_drop')]
>>> len(drops)
42

>>> # Access packet data
>>> event.packet.len
98

Script Locations

Scripts are searched in the following order:
  1. Exact path if provided (e.g., ./script.py)
  2. $HOME/.config/retis/python/script.py
  3. /usr/share/retis/python/script.py
You can provide just the script name without .py extension:
retis python my_analysis  # Searches for my_analysis.py

Script Arguments

Arguments are passed to scripts via sys.argv:
#!/usr/bin/env python3
import sys

if len(sys.argv) > 1:
    output_file = sys.argv[1]
    print(f"Writing to {output_file}")
Invoke with:
retis python script.py output.txt

Common Use Cases

Custom statistics

# Create a script to analyze packet distribution
retis python packet_distribution.py

Data export

# Export events to CSV
retis python export_csv.py output.csv

Correlation analysis

# Analyze timing between events
retis python timing_analysis.py

Integration with other tools

# Process events and send to external system
retis python send_to_elk.py --server elk.example.com

Python Dependencies

Scripts can import any Python modules available in your environment:
import pandas as pd
import matplotlib.pyplot as plt
from scapy.all import *

# Your analysis code
Install dependencies as needed:
pip install pandas matplotlib scapy

Performance Tips

  • For large event files, process events in batches
  • Use generators instead of loading all events in memory
  • Consider filtering events during collection to reduce file size

Error Handling

#!/usr/bin/env python3
import sys

try:
    for event in events:
        # Process event
        pass
except Exception as e:
    print(f"Error: {e}", file=sys.stderr)
    sys.exit(1)

See Also

  • collect - Collect events for analysis
  • print - View events in text format
  • sort - Sort events before analysis

Build docs developers (and LLMs) love