Planning a network traffic script
The user wants a Python script to monitor and visualize system network traffic. I’ll consider using libraries like psutil, scapy, or checking /proc/net/dev to read usage. For visualization, I’m thinking about matplotlib for live graphs or possibly a terminal chart. I'll outline the design and provide code, aiming for a version that works on multiple platforms. Psutil supports network stats, but I should clarify what kind of traffic the user wants to monitor. For now, I'll keep it simple.Designing the network monitoring script
I’m thinking of showing both the pure /proc method for Linux and having psutil as a fallback. However, that might be too detailed. Instead, I could propose a script using psutil and matplotlib to visualize real-time network I/O, while also logging data to a CSV file. It would make sense to incorporate argparse for settings like interval, interface, and duration. The focus should be on monitoring and visualizing network usage, likely without diving into packet-level sniffing.Setting up the script arguments
I’m outlining the command-line arguments for the script. We’ll have options for interface name, sampling interval, and number of samples.
In the script, I’ll import necessary libraries like time, argparse, collections, psutil, and matplotlib. First, I need to determine the network interface — defaulting to 'eth0' or the one with the highest initial traffic.
I’ll set up a Matplotlib figure to display upload and download lines over time, using a deque for tracking timestamps and values. The update function will resample network counters, compute deltas, and refresh the plot.Addressing edge cases and implementation
I need to consider some edge cases for the script. The first call should store baseline counters, and I’ll avoid updating the plot until the second iteration, starting from t0=0 with zero values.
To handle NIC names, I can print a list if a given interface isn't found or allow for interactive selection. For network load units, I think using Mbps makes sense, calculating it as Megabits = (bytes * 8) / 1e6 / interval. For smaller networks, maybe I’ll also display KB/s, but the graph will focus on Mbps.
I need to ensure the script is self-contained and provide full code, with a brief explanation of the approach and dependencies, as well as usage notes and possible extensions.Crafting the network monitor script
I need to keep the explanation short and focus on the essentials for the script. First, I'll set up the basic environment with required libraries and define a function to choose the default network interface.
The script should handle command-line arguments for the interface, sampling interval, and window size. If the interface isn’t provided, it will auto-detect one. I'll use psutil to gather network I/O counters and calculate upload and download speeds in real time, while also updating the plot dynamically with these values.
To avoid issues, I'll implement error handling for cases like missing interfaces. I'll also provide setup instructions for necessary libraries. The script will prioritize visualization, ensuring users can see real-time traffic metrics effectively. Below is a self-contained Python script that monitors system network throughput (upload/download) and visualizes it in real time using matplotlib.
It uses:
psutil for cross‑platform network stats
matplotlib for the live graph
1. Install dependencies
pip install psutil matplotlib
2. Script: net_monitor.py
#!/usr/bin/env python3
"""
Real-time network traffic monitor and visualizer.
Dependencies:
pip install psutil matplotlib
"""
import argparse
import time
from collections import deque
import psutil
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def list_interfaces():
"""Return a dict of interface -> is_up."""
stats = psutil.net_if_stats()
return {name: st.isup for name, st in stats.items()}
def pick_default_interface():
"""
Pick a reasonable default interface:
- Prefer first 'up' interface that is not loopback.
- Fallback to the first available interface.
"""
stats = psutil.net_if_stats()
if not stats:
raise RuntimeError("No network interfaces found.")
for name, st in stats.items():
lower = name.lower()
if st.isup and not lower.startswith(("lo", "loopback")):
return name
# Fallback: just return the first one
return next(iter(stats.keys()))
def parse_args():
parser = argparse.ArgumentParser(
description="Monitor and visualize network traffic in real-time."
)
parser.add_argument(
"-i",
"--interface",
help="Network interface to monitor (e.g. eth0, en0, Wi-Fi). "
"If omitted, a default active interface is chosen.",
)
parser.add_argument(
"-s",
"--sample-interval",
type=float,
default=1.0,
help="Sampling interval in seconds (default: 1.0)",
)
parser.add_argument(
"-w",
"--window",
type=int,
default=60,
help="Time window (in samples) to display in the graph (default: 60)",
)
return parser.parse_args()
def main():
args = parse_args()
# Determine interface
all_ifaces = list_interfaces()
if not all_ifaces:
raise SystemExit("No network interfaces detected.")
if args.interface:
iface = args.interface
if iface not in all_ifaces:
print(f"Interface '{iface}' not found.")
print("Available interfaces:")
for name, up in all_ifaces.items():
state = "UP" if up else "DOWN"
print(f" - {name} ({state})")
raise SystemExit(1)
else:
iface = pick_default_interface()
print(f"No interface specified, using default: {iface}")
print(f"Monitoring interface: {iface}")
print(f"Sampling interval : {args.sample_interval}s")
print(f"Window size : {args.window} samples")
print("Close the graph window or press Ctrl+C to stop.\n")
# Initial counters
try:
prev_counters = psutil.net_io_counters(pernic=True)[iface]
except KeyError:
raise SystemExit(f"Interface '{iface}' disappeared or is not available.")
prev_time = time.time()
# Data buffers
x_data = deque(maxlen=args.window) # time (seconds since start)
up_data = deque(maxlen=args.window) # upload Mbps
down_data = deque(maxlen=args.window) # download Mbps
start_time = prev_time
# Set up the plot
plt.style.use("seaborn-v0_8-darkgrid")
fig, ax = plt.subplots()
line_up, = ax.plot([], [], label="Upload (Mbit/s)", color="tab:red")
line_down, = ax.plot([], [], label="Download (Mbit/s)", color="tab:blue")
text_cur = ax.text(
0.01,
0.95,
"",
transform=ax.transAxes,
ha="left",
va="top",
fontsize=9,
bbox=dict(boxstyle="round", facecolor="white", alpha=0.7),
)
ax.set_xlabel("Time (s)")
ax.set_ylabel("Throughput (Mbit/s)")
ax.set_title(f"Real-time Network Traffic on {iface}")
ax.legend(loc="upper right")
def update(_frame):
nonlocal prev_counters, prev_time
now = time.time()
try:
counters = psutil.net_io_counters(pernic=True)[iface]
except KeyError:
print(f"Interface '{iface}' no longer available; stopping.")
plt.close(fig)
return line_up, line_down, text_cur
elapsed = now - prev_time
if elapsed <= 0:
# Avoid division by zero; skip this frame
return line_up, line_down, text_cur
# Byte deltas
bytes_sent = counters.bytes_sent - prev_counters.bytes_sent
bytes_recv = counters.bytes_recv - prev_counters.bytes_recv
# Convert to Mbps (megabits per second)
up_mbps = (bytes_sent * 8.0) / (1e6 * elapsed)
down_mbps = (bytes_recv * 8.0) / (1e6 * elapsed)
# Update previous
prev_counters = counters
prev_time = now
# Append to buffers
t = now - start_time
x_data.append(t)
up_data.append(up_mbps)
down_data.append(down_mbps)
# Update lines
line_up.set_data(x_data, up_data)
line_down.set_data(x_data, down_data)
# Adjust axes limits
if x_data:
xmin = max(0, x_data[0])
xmax = x_data[-1] if len(x_data) > 1 else xmin + 1
ax.set_xlim(xmin, xmax)
ymax = max(
max(up_data, default=0.1),
max(down_data, default=0.1),
0.1,
)
ax.set_ylim(0, ymax * 1.2)
# Update info text
text_cur.set_text(
f"Current: Up {up_mbps:6.2f} Mbit/s "
f"Down {down_mbps:6.2f} Mbit/s"
)
# Also log a simple line to the console
print(
f"[{t:6.1f}s] Up: {up_mbps:7.3f} Mbit/s "
f"Down: {down_mbps:7.3f} Mbit/s",
end="\r",
flush=True,
)
return line_up, line_down, text_cur
ani = animation.FuncAnimation(
fig,
update,
interval=int(args.sample_interval * 1000),
blit=False,
)
try:
plt.show()
except KeyboardInterrupt:
print("\nInterrupted by user.")
if __name__ == "__main__":
main()
3. Usage examples
List interfaces:
import psutil
print(psutil.net_if_stats().keys())
Run monitor with default interface:
python net_monitor.py
Specify interface and tweak settings:
python net_monitor.py -i eth0 -s 0.5 -w 120
# or on macOS/Windows, for example:
python net_monitor.py -i "Wi-Fi" -s 1 -w 60
If you tell me your OS and what level of detail you want (per-interface, per-process, packet-level), I can adapt this to your exact needs.