|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Cross-platform script to kill processes using specific ports. |
| 4 | +Usage: kill_port.py <port1> [port2] [port3] ... |
| 5 | +""" |
| 6 | + |
| 7 | +import sys |
| 8 | +import subprocess |
| 9 | +import platform |
| 10 | +import re |
| 11 | + |
| 12 | + |
| 13 | +def kill_processes_on_port(port): |
| 14 | + """Kill all processes using the specified port.""" |
| 15 | + system = platform.system().lower() |
| 16 | + |
| 17 | + try: |
| 18 | + if system in ["linux", "darwin"]: # Linux or macOS |
| 19 | + # Try lsof first (most reliable) |
| 20 | + try: |
| 21 | + result = subprocess.run( |
| 22 | + ["lsof", "-ti", f":{port}"], |
| 23 | + capture_output=True, |
| 24 | + text=True, |
| 25 | + check=False, |
| 26 | + ) |
| 27 | + if result.returncode == 0 and result.stdout.strip(): |
| 28 | + pids = result.stdout.strip().split("\n") |
| 29 | + for pid in pids: |
| 30 | + if pid.strip(): |
| 31 | + subprocess.run(["kill", "-9", pid.strip()], check=False) |
| 32 | + except FileNotFoundError: |
| 33 | + # Fall back to netstat if lsof not available |
| 34 | + result = subprocess.run(["netstat", "-tlnp"], capture_output=True, text=True, check=False) |
| 35 | + if result.returncode == 0: |
| 36 | + for line in result.stdout.split("\n"): |
| 37 | + if f":{port} " in line: |
| 38 | + # Extract PID from output like "tcp 0 0 :::8080 :::* LISTEN 12345/python" |
| 39 | + match = re.search(r"(\d+)/", line) |
| 40 | + if match: |
| 41 | + pid = match.group(1) |
| 42 | + subprocess.run(["kill", "-9", pid], check=False) |
| 43 | + |
| 44 | + elif system == "windows": |
| 45 | + # Windows using netstat and taskkill |
| 46 | + result = subprocess.run(["netstat", "-ano"], capture_output=True, text=True, check=False) |
| 47 | + if result.returncode == 0: |
| 48 | + for line in result.stdout.split("\n"): |
| 49 | + if f":{port} " in line and "LISTENING" in line: |
| 50 | + # Extract PID from last column |
| 51 | + parts = line.split() |
| 52 | + if len(parts) >= 5: |
| 53 | + pid = parts[-1] |
| 54 | + if pid.isdigit(): |
| 55 | + subprocess.run( |
| 56 | + ["taskkill", "/PID", pid, "/F"], |
| 57 | + check=False, |
| 58 | + capture_output=True, |
| 59 | + ) |
| 60 | + |
| 61 | + except Exception as e: |
| 62 | + # Silently continue - port cleanup is best effort |
| 63 | + pass |
| 64 | + |
| 65 | + |
| 66 | +def main(): |
| 67 | + if len(sys.argv) < 2: |
| 68 | + print("Usage: kill_port.py <port1> [port2] [port3] ...") |
| 69 | + sys.exit(1) |
| 70 | + |
| 71 | + for port_str in sys.argv[1:]: |
| 72 | + try: |
| 73 | + port = int(port_str) |
| 74 | + kill_processes_on_port(port) |
| 75 | + except ValueError: |
| 76 | + print(f"Warning: Invalid port number '{port_str}'") |
| 77 | + |
| 78 | + |
| 79 | +if __name__ == "__main__": |
| 80 | + main() |
0 commit comments