TCP连接Python脚本 | AI生成和翻译

Home 2025.05

PowerShell 命令 Get-NetTCPConnection -LocalPort 80 用于获取 Windows 系统中使用指定本地端口(此处为端口 80)的 TCP 连接信息。要在 Python 中实现类似功能,可以使用 psutil 库,该库提供了跨平台访问系统详细信息(包括网络连接)的能力。

以下是一个 Python 脚本示例,用于按特定本地端口(如端口 80)筛选并列出 TCP 连接,功能类似于上述 PowerShell 命令:

import psutil

def get_tcp_connections_by_port(local_port):
    # 获取所有网络连接
    connections = psutil.net_connections(kind='tcp')
    
    # 按本地端口筛选连接
    matching_connections = [
        conn for conn in connections
        if conn.laddr.port == local_port and conn.status == 'LISTEN'
    ]
    
    # 打印匹配连接的详细信息
    if not matching_connections:
        print(f"未找到在端口 {local_port} 监听的 TCP 连接")
        return
    
    print(f"在端口 {local_port} 监听的 TCP 连接:")
    print("PID\t本地地址\t\t远程地址\t\t状态")
    print("-" * 50)
    
    for conn in matching_connections:
        local_addr = f"{conn.laddr.ip}:{conn.laddr.port}" if conn.laddr else "N/A"
        remote_addr = f"{conn.raddr.ip}:{conn.raddr.port}" if conn.raddr else "N/A"
        pid = conn.pid if conn.pid is not None else "N/A"
        status = conn.status if conn.status else "N/A"
        print(f"{pid}\t{local_addr}\t{remote_addr}\t{status}")

if __name__ == "__main__":
    target_port = 80  # 指定要筛选的端口(例如 80)
    get_tcp_connections_by_port(target_port)

说明:

  1. 安装 psutil
    • 需要安装 psutil 库才能访问网络连接详细信息。可通过以下命令安装:
      pip install psutil
      
  2. 脚本详情
    • psutil.net_connections(kind='tcp') 获取所有 TCP 连接
    • 脚本会筛选本地端口与指定 local_port(如 80)匹配且状态为 LISTEN 的连接(用于模拟 Get-NetTCPConnection 对监听端口的行为)
    • 对每个匹配的连接,会打印以下信息:
      • PID:使用该连接的进程 ID
      • 本地地址:本地 IP 和端口
      • 远程地址:远程 IP 和端口(如适用;未连接时显示 “N/A”)
      • 状态:连接状态(如 “LISTEN”)
  3. 输出
    • 输出格式模拟 Get-NetTCPConnection 的表格形式,显示 PID、本地地址、远程地址和状态

示例输出:

如果有 Web 服务器(如 Apache 或 Nginx)正在端口 80 监听,输出可能如下:

在端口 80 监听的 TCP 连接:
PID     本地地址            远程地址           状态
--------------------------------------------------
1234    0.0.0.0:80         N/A               LISTEN

如果端口 80 没有监听进程:

未找到在端口 80 监听的 TCP 连接

注意事项:

此脚本提供了与 PowerShell 命令等效的 Python 实现,具有相似的功能和输出。如果您需要额外功能或有特定需求,请随时告知!


Back Donate