To monitor network traffic in Python, you can use the psutil library, which provides a convenient interface to retrieve information on system utilization, including network-related data.
Here’s a simple example of a Python script that monitors network traffic:
import psutil
import time
def get_network_usage(interval=1):
while True:
try:
net_stats = psutil.net_io_counters()
bytes_sent = net_stats.bytes_sent
bytes_received = net_stats.bytes_recv
print(f"Bytes Sent: {bytes_sent} B")
print(f"Bytes Received: {bytes_received} B")
print("------")
time.sleep(interval)
except KeyboardInterrupt:
print("\nMonitoring stopped.")
break
if __name__ == "__main__":
get_network_usage()
In this script:
- psutil.net_io_counters() retrieves network I/O statistics.
- bytes_sent represents the total number of bytes sent over the network.
- bytes_received represents the total number of bytes received over the network.
The script prints these values in a loop with a specified interval (default is 1 second). You can adjust the interval parameter to control how frequently the network statistics are printed.
To run this script, you need to install the psutil library:
pip install psutil
For more advanced network monitoring and analysis, consider exploring tools and libraries specifically designed for this purpose. This script provides a basic example.