Kill Process on Port with Psutil | Generated by AI

Home 2025.10

Using psutil to Detect and Kill a Process on a Specific Port (Windows)

Psutil is a cross-platform Python library for retrieving information on running processes and system utilization. You can use it to find processes listening on a specific port (e.g., identifying if something like an npm dev server is running on that port) and then terminate the process. This works on Windows, but keep in mind:

Step 1: Install psutil

If you haven’t already:

pip install psutil

Step 2: Sample Code to Detect and Kill

Here’s a complete Python script. It defines a function to find the PID of the process listening on a given port (using kind='inet' as you specified), then terminates it. On Windows, terminate() is preferred over kill() as it allows graceful shutdown (equivalent to SIGTERM on Unix).

import psutil
import time  # For optional delay

def get_pid_listening_on_port(port, kind='inet'):
    """
    Scans network connections for processes listening on the specified port.
    Returns a list of PIDs (usually one, but could be multiple if rare).
    """
    pids = []
    for conn in psutil.net_connections(kind=kind):
        # Check if it's a listening connection (status='LISTEN') and the local address port matches
        if conn.status == 'LISTEN' and conn.laddr and conn.laddr.port == port:
            if conn.pid:
                pids.append(conn.pid)
    return pids

def kill_process_on_port(port, kind='inet'):
    """
    Finds and terminates the process listening on the specified port.
    If multiple processes, kills all (with a warning).
    """
    pids = get_pid_listening_on_port(port, kind)
    if not pids:
        print(f"No process found listening on port {port}.")
        return
    
    for pid in pids:
        try:
            proc = psutil.Process(pid)
            print(f"Terminating process {proc.name()} (PID {pid}) on port {port}...")
            # Use terminate() for graceful shutdown; it sends a SIGTERM-like signal
            proc.terminate()
            # Optional: Wait a bit and force kill if it doesn't exit
            gone, still_alive = psutil.wait_procs([proc], timeout=3)
            if still_alive:
                print(f"Force killing PID {pid}...")
                still_alive[0].kill()
        except psutil.AccessDenied:
            print(f"Access denied: Cannot terminate PID {pid}. Run as administrator?")
        except psutil.NoSuchProcess:
            print(f"Process {pid} no longer exists.")

# Example usage: Replace 3000 with your target port (e.g., npm dev servers often use 3000)
if __name__ == "__main__":
    kill_process_on_port(3000)  # Adjust kind if needed (e.g., 'inet4' for IPv4 only)

Key Explanations

If this doesn’t match your exact need (e.g., if “npm run port” means something else or you want to detect non-listening connections), provide more details for refinement! For security/tsafety, ensure you’re only killing intended processes.


Back

x-ai/grok-code-fast-1

Donate