Build a Python script to monitor and visualize system network traffic.
- User
Build a Python script to monitor and visualize system network traffic.
Assistant
Examining the Core Problem
I'm now zeroing in on the precise requirements for capturing network traffic. I need a mechanism to pull the byte counts for both sent and received data. It seems I should also include interface name so it can be associated with the interface name. I am currently considering a few Python libraries that could simplify this task, such as
psutilor potentially raw sockets.Refining the Approach
I've decided to employ
psutilfor data acquisition andmatplotlibfor visualization, specifically using itsanimationmodule. My current focus is on the program's logic, outlined steps: grab initial counters, wait a second, grab new counters, calculate speed, store, and update the plot. I'm now drafting the implementation code based on this structure, starting with the necessary imports and configuration parameters.Developing the Implementation
I'm now concretizing the animation logic and data acquisition details. I've defined constants for the update interval and lookback period. I'll use lists to store time and speed values. The
get_speed()function will track the state of counters. Instead of relying on a dedicated function, I'll streamline the speed calculation within the animation loop using global variables for the previous state. Within theanimate(i)function, I'll retrieve current bytes, calculate the speed difference from the previous state, convert the result to a usable scale, append the values to appropriate lists, and constrain the lists within the lookback window.Finalizing the Visualization
I'm now implementing the
set_datamethod for optimized plotting performance. I've initialized lists for upload and download data and integrated thepsutilcounters. The update function is nearly complete, and I'm currently adding the logic to calculate the difference between the current and last byte counts and update the plot with the new data. I'm focusing on ensuring smooth visualization without flickering.Adding Final Polish
I am now focusing on refining the user experience. I've integrated a byte formatting function to present speeds in a readable format. Furthermore, I've implemented a visually appealing dark style for the plot, aiming for a modern, techy look. To make the program more user-friendly, I am also ensuring graceful handling of
KeyboardInterruptevents. The final structure encompasses library imports, global variables, the formatting function, theanimatefunction, figure setup, animation execution, and plot display. I've reviewed the design, confirming its cross-platform capability and real-time data visualization throughanimationwith onlypsutilandmatplotlibdependencies.Improving Accessibility and Clarity
I'm now incorporating detailed comments and explanations throughout the code to enhance understanding and make it easier to follow. I've added instructions on installing dependencies, including matplotlib. I've also included a "terminal-only" alternative for those who prefer it. Finally, I've confirmed that all variables are initialized correctly, and that the calculations are accurate. I've chosen the
ax.clear()method for dynamically scaled Y-axes in the animation function, which is critical for smooth traffic visualization.Refining Output Structure
I'm now integrating final polish touches, including output naming conventions and checking for clarity in formatting. I've re-reviewed the final program, confirming it incorporates all required features and adheres to the established design principles. My next step will be to confirm its output, which, if correct, would mark completion. I'm focusing on ensuring all aspects of the code, from variable naming to output formatting, are optimized for clarity and user-friendliness.
Here is a complete Python script to monitor network traffic and visualize it in real-time using
matplotlibandpsutil.Prerequisites
You will need to install two libraries:
- psutil: To retrieve system network statistics.
- matplotlib: To plot the graph.
Run this command in your terminal:
pip install psutil matplotlibThe Python Script
Save the following code as
net_monitor.py.import psutil import matplotlib.pyplot as plt import matplotlib.animation as animation import time # Configuration UPDATE_INTERVAL = 1000 # Update every 1000ms (1 second) MAX_POINTS = 60 # Keep last 60 seconds of data # Initialize data lists x_vals = [] y_dl = [] y_ul = [] # Initialize global trackers last_rec = psutil.net_io_counters().bytes_recv last_sent = psutil.net_io_counters().bytes_sent last_time = time.time() # Create figure and axis fig = plt.figure() ax = fig.add_subplot(1, 1, 1) plt.style.use('fivethirtyeight') # Use a visually appealing style def format_bytes(size): """Helper to convert bytes to readable format (KB, MB, GB)""" power = 2**10 n = 0 power_labels = {0 : '', 1: 'K', 2: 'M', 3: 'G', 4: 'T'} while size > power: size /= power n += 1 return f"{size:.2f} {power_labels[n]}B/s" def animate(i): global last_rec, last_sent, last_time # Get current stats current_rec = psutil.net_io_counters().bytes_recv current_sent = psutil.net_io_counters().bytes_sent current_time = time.time() # Calculate time difference to ensure accuracy even if lag occurs time_delta = current_time - last_time if time_delta == 0: time_delta = 1 # Avoid division by zero # Calculate speed (Bytes per second) # (Current - Last) / Time Elapsed dl_speed = (current_rec - last_rec) / time_delta ul_speed = (current_sent - last_sent) / time_delta # Update globals for next iteration last_rec = current_rec last_sent = current_sent last_time = current_time # Append data x_vals.append(i) y_dl.append(dl_speed) y_ul.append(ul_speed) # Limit lists to MAX_POINTS if len(x_vals) > MAX_POINTS: x_vals.pop(0) y_dl.pop(0) y_ul.pop(0) # clear axis ax.clear() # Plot data # We divide by 1024 to plot in KB/s roughly for the Y-axis scale, # or keep as raw bytes and format the labels. # Here we plot raw bytes but label the current speed in the legend. ax.plot(x_vals, y_dl, label=f'Download ({format_bytes(dl_speed)})', linewidth=2) ax.plot(x_vals, y_ul, label=f'Upload ({format_bytes(ul_speed)})', linewidth=2) # Formatting ax.set_title('Live Network Traffic') ax.set_ylabel('Speed (Bytes/sec)') ax.set_xlabel('Time (seconds)') ax.legend(loc='upper left') ax.grid(True) # Improve Y-axis formatting to show readable units instead of scientific notation # This adjusts the Y-axis labels dynamically def y_fmt(x, y): return format_bytes(x) ax.yaxis.set_major_formatter(plt.FuncFormatter(y_fmt)) plt.tight_layout() print("Starting Network Monitor... (Close the graph window to stop)") # Set up animation ani = animation.FuncAnimation(fig, animate, interval=UPDATE_INTERVAL) plt.show()How it Works
- Initialization: We record the initial "total bytes sent/received" provided by the OS.
- The
animatefunction: This function runs every 1 second (1000ms). - Delta Calculation:
- It captures the new total bytes.
- It subtracts the old total bytes from the new ones to find out how many bytes were transferred in that specific second.
- Buffering: It stores these speeds in a list. If the list gets longer than 60 entries (60 seconds), it removes the oldest entry to create a "moving window" effect.
- Plotting:
ax.clear()wipes the previous frame.- We plot the Download and Upload lines.
ax.yaxis.set_major_formatterensures the Y-axis shows "MB/s" or "KB/s" instead of raw numbers like1048576.
Customization
- Change Plot Style: Change
plt.style.use('fivethirtyeight')to'Solarize_Light2','bmh', or'dark_background'for different looks. - Specific Interface: By default,
psutil.net_io_counters()grabs traffic for all interfaces combined (Wi-Fi + Ethernet). If you want a specific interface (e.g., Wi-Fi only):- Change the code to use
psutil.net_io_counters(pernic=True). - Access the specific dictionary key, e.g.,
['Wi-Fi']or['eth0'].
- Change the code to use
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.