Python Script for TCP Connections | Generated by AI

Home PDF

The PowerShell command Get-NetTCPConnection -LocalPort 80 retrieves information about TCP connections on a Windows system that are using the specified local port (in this case, port 80). To achieve similar functionality in Python, you can use the psutil library, which provides cross-platform access to system details, including network connections.

Below is a Python script that lists TCP connections filtered by a specific local port (e.g., port 80), similar to the PowerShell command:

import psutil

def get_tcp_connections_by_port(local_port):
    # Retrieve all network connections
    connections = psutil.net_connections(kind='tcp')
    
    # Filter connections by local port
    matching_connections = [
        conn for conn in connections
        if conn.laddr.port == local_port and conn.status == 'LISTEN'
    ]
    
    # Print details of matching connections
    if not matching_connections:
        print(f"No TCP connections found listening on port {local_port}")
        return
    
    print(f"TCP connections listening on port {local_port}:")
    print("PID\tLocal Address\tRemote Address\tStatus")
    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  # Specify the port to filter (e.g., 80)
    get_tcp_connections_by_port(target_port)

Explanation:

  1. Install psutil:
    • You need the psutil library to access network connection details. Install it using:
      pip install psutil
      
  2. Script Details:
    • psutil.net_connections(kind='tcp') retrieves all TCP connections.
    • The script filters connections where the local port matches the specified local_port (e.g., 80) and the status is LISTEN (to mimic the behavior of Get-NetTCPConnection for listening ports).
    • For each matching connection, it prints:
      • PID: Process ID of the application using the connection.
      • Local Address: Local IP and port.
      • Remote Address: Remote IP and port (if applicable; “N/A” if not connected).
      • Status: Connection status (e.g., “LISTEN”).
  3. Output:
    • The output is formatted to resemble the tabular output of Get-NetTCPConnection, showing the PID, local address, remote address, and status.

Example Output:

If a web server (e.g., Apache or Nginx) is listening on port 80, the output might look like this:

TCP connections listening on port 80:
PID     Local Address         Remote Address        Status
--------------------------------------------------
1234    0.0.0.0:80            N/A                   LISTEN

If no process is listening on port 80:

No TCP connections found listening on port 80

Notes:

This script provides a Python equivalent to the PowerShell command, with similar functionality and output. If you need additional features or have specific requirements, let me know!


Back 2025.05.28 Donate