Skip to content

Instantly share code, notes, and snippets.

@chuongmep
Created June 20, 2024 12:16
Show Gist options
  • Save chuongmep/f43b8ae0381c43025c636a6e5b784bc7 to your computer and use it in GitHub Desktop.
Save chuongmep/f43b8ae0381c43025c636a6e5b784bc7 to your computer and use it in GitHub Desktop.
import psutil
def get_all_ports():
ports = set()
for proc in psutil.process_iter(['pid', 'name']):
try:
connections = proc.net_connections()
for conn in connections:
if conn.laddr.port:
ports.add(conn.laddr.port)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
return ports
if __name__ == "__main__":
ports_in_use = get_all_ports()
print("Ports in use:")
for port in sorted(ports_in_use):
print(port)
@chuongmep
Copy link
Author

chuongmep commented Jun 20, 2024

kill ports :

import psutil

def kill_process_on_port(port):
    # Iterate over all processes
    for proc in psutil.process_iter(['pid', 'name']):
        try:
            # Get all network connections of the process
            connections = proc.net_connections()
            # Check each connection to see if it's on the specified port
            for conn in connections:
                if conn.laddr.port == port:
                    print(f"Killing process {proc.name()} with PID {proc.pid} on port {port}")
                    proc.kill()  # Kill the process
                    proc.wait()  # Wait for the process to be terminated
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            # Handle processes that could not be accessed
            continue

if __name__ == "__main__":
    kill_process_on_port(8000)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment