-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkill_ports.py
More file actions
163 lines (139 loc) · 5.41 KB
/
kill_ports.py
File metadata and controls
163 lines (139 loc) · 5.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#!/usr/bin/env python3
"""
Kill Ports Script
Force kill any processes using TastyBot ports (3000, 8000, 8001)
"""
import subprocess
import sys
import re
from typing import List, Tuple
# Ports to check and kill
PORTS = [8765, 8766 ]
def get_processes_using_port(port: int) -> List[Tuple[str, str]]:
"""Get list of (PID, process_name) using the specified port"""
try:
# Run netstat to find processes using the port
result = subprocess.run(
['netstat', '-ano'],
capture_output=True,
text=True,
check=True
)
processes = []
for line in result.stdout.split('\n'):
if f':{port}' in line and 'LISTENING' in line:
# Extract PID from the line
parts = line.split()
if len(parts) >= 5:
pid = parts[-1]
if pid != '0' and pid.isdigit():
# Get process name
try:
tasklist_result = subprocess.run(
['tasklist', '/FI', f'PID eq {pid}', '/FO', 'CSV'],
capture_output=True,
text=True,
check=True
)
# Parse CSV output to get process name
lines = tasklist_result.stdout.strip().split('\n')
if len(lines) > 1: # Skip header
process_info = lines[1].split(',')
if len(process_info) > 0:
process_name = process_info[0].strip('"')
processes.append((pid, process_name))
except subprocess.CalledProcessError:
processes.append((pid, "Unknown"))
return processes
except subprocess.CalledProcessError as e:
print(f"Error running netstat: {e}")
return []
def kill_process(pid: str, process_name: str) -> bool:
"""Kill a process by PID"""
try:
subprocess.run(
['taskkill', '/F', '/PID', pid],
capture_output=True,
text=True,
check=True
)
print(f"[KILLED] PID {pid} ({process_name})")
return True
except subprocess.CalledProcessError as e:
print(f"[ERROR] Failed to kill PID {pid} ({process_name}): {e}")
return False
def kill_processes_by_name(process_names: List[str]) -> int:
"""Kill processes by name, return count of killed processes"""
killed_count = 0
for process_name in process_names:
try:
result = subprocess.run(
['taskkill', '/F', '/IM', process_name],
capture_output=True,
text=True
)
if result.returncode == 0:
print(f"[KILLED] All {process_name} processes")
killed_count += 1
elif "not found" not in result.stderr.lower():
print(f"[INFO] No {process_name} processes found")
except subprocess.CalledProcessError as e:
print(f"[ERROR] Failed to kill {process_name}: {e}")
return killed_count
def main():
"""Main function to kill processes on specified ports"""
print("TastyBot Port Killer")
print("=" * 40)
print(f"Checking ports: {', '.join(map(str, PORTS))}")
print()
total_killed = 0
# Check each port
for port in PORTS:
print(f"Checking port {port}...")
processes = get_processes_using_port(port)
if not processes:
print(f"[OK] No processes found using port {port}")
continue
print(f"[FOUND] {len(processes)} process(es) using port {port}:")
for pid, process_name in processes:
print(f" - PID {pid}: {process_name}")
# Kill each process
for pid, process_name in processes:
if kill_process(pid, process_name):
total_killed += 1
print()
# Also kill common development server processes
print("Killing common development processes...")
dev_processes = ['python.exe', 'node.exe', 'uvicorn.exe']
killed_count = kill_processes_by_name(dev_processes)
total_killed += killed_count
print(f"\nSummary: Killed {total_killed} process(es)")
# Verify ports are clear
print("\nVerifying ports are clear...")
any_remaining = False
for port in PORTS:
processes = get_processes_using_port(port)
if processes:
print(f"[WARNING] Port {port} still has {len(processes)} process(es)")
any_remaining = True
else:
print(f"[OK] Port {port} is clear")
if any_remaining:
print("\n[WARNING] Some ports still have processes. You may need to:")
print("1. Close applications manually")
print("2. Restart your computer")
print("3. Check for services using these ports")
return 1
else:
print("\n[SUCCESS] All ports are clear!")
return 0
if __name__ == "__main__":
try:
exit_code = main()
sys.exit(exit_code)
except KeyboardInterrupt:
print("\nAborted by user")
sys.exit(1)
except Exception as e:
print(f"[ERROR] Unexpected error: {e}")
sys.exit(1)