如何使用Python列出新增TCP连接?(附现有全连接查询代码)
Got it, let's break down how to modify your existing code to track new TCP connections over time using a continuous loop. Here's a practical, efficient approach:
Core Idea
We'll maintain a set of already-seen connections. On each loop iteration, we'll compare the current list of TCP connections against this set—any connection not in the set is a new one we need to report. Then we'll update the set to include these new connections for future checks.
Complete Code
import psutil import time def get_tcp_connections(): # Return a set of remote addresses (matches your original code's connection[5]) try: # Use 'inet' to cover IPv4/IPv6; use 'tcp' if you only want TCP connections connections = psutil.net_connections(kind='inet') return {conn.raddr for conn in connections if conn.raddr} # Filter empty remote addresses except psutil.AccessDenied: print("Error: Need root privileges to access connection details. Run with sudo.") exit(1) # Initialize the set with existing connections seen_connections = get_tcp_connections() print("Monitoring new TCP connections... (Press Ctrl+C to stop)") try: while True: current_connections = get_tcp_connections() # Find connections that are in current but not in seen new_connections = current_connections - seen_connections for conn in new_connections: print(f"New TCP connection detected: {conn}") # Update the seen set to include current connections seen_connections.update(current_connections) # Wait before next check (adjust interval as needed) time.sleep(1) except KeyboardInterrupt: print("\nStopped monitoring.")
Key Details Explained
- Set for Tracking: Using a
setinstead of a list makes checking for existing connections much faster (O(1) lookups vs O(n) for lists), which matters if you have many active connections. - Error Handling: Added a check for
AccessDeniedbecausepsutil.net_connectionsrequires root privileges on most Unix-like systems (Linux/macOS). You'll need to run the script withsudoto avoid this error. - Connection Filtering: We filter out connections with empty
raddr(remote address) because these are often local listening sockets, not active outgoing/incoming connections. Remove theif conn.raddrcheck if you want to include them. - Loop Interval: The
time.sleep(1)adds a 1-second delay between checks. Increase this (e.g.,5for 5 seconds) to reduce CPU usage, or decrease it if you need more frequent monitoring.
Optional Enhancements
If you want more detailed connection context instead of just the remote address, modify the get_tcp_connections function to return unique identifiers with extra details:
def get_tcp_connections(): connections = psutil.net_connections(kind='inet') return {(conn.laddr, conn.raddr, conn.status) for conn in connections if conn.raddr}
This tracks combinations of local address, remote address, and connection status (e.g., ESTABLISHED, SYN_SENT), giving you richer info about each new connection.
内容的提问来源于stack exchange,提问作者Aviral Srivastava

