"""
Network Traffic Monitor and Visualizer
======================================
This Python script uses `psutil` to monitor total system network I/O (upload/download)
and `matplotlib` to visualize the traffic rates in KB/s over time in a live-updating plot.
Features:
- Real-time monitoring of cumulative bytes sent/received.
- Computes and plots traffic rates (KB/s) for upload (green) and download (blue).
- Rolling window of the last 60 seconds (1-second intervals).
- Cross-platform (Windows, Linux, macOS).
Requirements:
- Python 3.6+
- Install dependencies: `pip install psutil matplotlib`
Usage:
- Run the script: `python network_monitor.py`
- The plot updates every second.
- Close the window to stop.
Note: This monitors total network I/O across all interfaces. Rates are calculated as deltas
between samples to show instantaneous throughput.
"""
import psutil
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import time
# Configure the plot
fig, ax = plt.subplots(figsize=(12, 6))
plt.style.use('dark_background') # Dark theme for better visibility
# Data storage (rolling window)
times = []
upload_rates = [] # KB/s
download_rates = [] # KB/s
prev_stats = None
prev_time = None
start_time = time.time()
def update(frame):
"""
Update function for matplotlib animation.
Fetches network stats, computes rates, and redraws the plot.
"""
global prev_stats, prev_time
# Get current network I/O counters (total across all interfaces)
stats = psutil.net_io_counters()
now = time.time()
# Compute rates if we have previous data
if prev_stats is not None and prev_time is not None:
delta_time = now - prev_time
if delta_time > 0:
upload_rate_kb_s = (stats.bytes_sent - prev_stats.bytes_sent) / delta_time / 1024
download_rate_kb_s = (stats.bytes_recv - prev_stats.bytes_recv) / delta_time / 1024
# Append data (relative time for x-axis)
rel_time = now - start_time
times.append(rel_time)
upload_rates.append(upload_rate_kb_s)
download_rates.append(download_rate_kb_s)
# Maintain rolling window of 60 points (~1 minute at 1s intervals)
if len(times) > 60:
times.pop(0)
upload_rates.pop(0)
download_rates.pop(0)
# Update previous values
prev_stats = stats
prev_time = now
# Clear and redraw
ax.clear()
# Plot if we have data
if times:
ax.plot(times, upload_rates, label='Upload (KB/s)', color='lime', linewidth=2)
ax.plot(times, download_rates, label='Download (KB/s)', color='cyan', linewidth=2)
# Styling
ax.set_title('System Network Traffic Monitor (Total I/O Rates)', fontsize=16, color='white', pad=20)
ax.set_xlabel('Time (seconds)', fontsize=12, color='white')
ax.set_ylabel('Traffic Rate (KB/s)', fontsize=12, color='white')
ax.legend(loc='upper right', fontsize=11)
ax.grid(True, alpha=0.3)
ax.set_facecolor('black')
fig.patch.set_facecolor('black')
# Dynamic y-axis limits for better scaling
if upload_rates or download_rates:
all_rates = upload_rates + download_rates
margin = max(all_rates) * 0.1 if all_rates else 1
ax.set_ylim(0, max(all_rates) + margin)
# Create animation: update every 1000ms (1 second)
ani = FuncAnimation(fig, update, interval=1000, cache_frame_data=False, blit=False)
# Show the plot (blocks until closed)
plt.tight_layout()
plt.show()
How to Run
- Save the code to a file, e.g.,
network_monitor.py.
- Install dependencies:
pip install psutil matplotlib
- Run:
python network_monitor.py
Customization Ideas
- Per-Interface Monitoring: Change
psutil.net_io_counters() to psutil.net_io_counters(pernic=True) and sum/loop over interfaces.
- Export Data: Add CSV logging in
update().
- Alerts: Add thresholds to print warnings for high traffic.
- GUI Controls: Use
matplotlib.widgets for pause/reset buttons.
This script is lightweight, efficient, and provides a smooth real-time visualization! If you need enhancements, let me know.