You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python列出新增TCP连接?(附现有全连接查询代码)

Detect New TCP Connections Continuously with Python & psutil

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 set instead 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 AccessDenied because psutil.net_connections requires root privileges on most Unix-like systems (Linux/macOS). You'll need to run the script with sudo to 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 the if conn.raddr check if you want to include them.
  • Loop Interval: The time.sleep(1) adds a 1-second delay between checks. Increase this (e.g., 5 for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:43:38