乐闻世界logo
搜索文章和话题

how to get network traffic per connection using python

1个答案

1

When using Python to retrieve network traffic for each connection, multiple approaches can be employed. Here, I'll cover two common methods: utilizing third-party libraries such as psutil, and leveraging built-in operating system tools along with Python's standard library for parsing.

Method One: Using the psutil Library

psutil (process and system utilities) is a cross-platform library for retrieving information about running processes and system utilization (such as CPU, memory, disk, and network). Specifically, for network-related data, psutil offers straightforward APIs.

Installation:

bash
pip install psutil

Code Example:

python
import psutil # Retrieve overall network statistics total_net_io = psutil.net_io_counters() print(f"Total received bytes: {total_net_io.bytes_recv}, Total sent bytes: {total_net_io.bytes_sent}") # Retrieve statistics grouped by network connection per_conn_stats = psutil.net_connections(kind='inet') for conn in per_conn_stats: print(f"Local address: {conn.laddr}, Remote address: {conn.raddr}, Status: {conn.status}")

The psutil.net_connections() method returns all network connection information on the system. Each connection includes details such as local address, remote address, and status, which helps in understanding the state of each TCP/UDP connection.

Method Two: Using Operating System Commands

For Linux and other Unix-like systems, we can use commands such as netstat or ss to obtain detailed information about network connections, and then call these commands via Python to parse the output.

Code Example:

python
import subprocess def get_network_traffic(): # Execute netstat command result = subprocess.run(['netstat', '-tunap'], capture_output=True, text=True) # Parse the result if result.returncode == 0: for line in result.stdout.split('\n'): print(line) else: print("Error executing netstat") get_network_traffic()

In this example, we use subprocess.run() to execute the netstat command. By parsing the output of netstat, we can obtain details such as the state of each connection and the ports being used.

Summary

The choice depends on specific requirements and environment. For most applications, using psutil is more convenient as it is cross-platform and provides easy-to-use APIs. However, if you need lower-level information or are in certain specific environments, directly using operating system commands may be more suitable. In practice, understanding the pros and cons of various methods and their applicable scenarios is crucial for selecting the most appropriate solution.

2024年7月28日 19:47 回复

你的答案