Repository navigation
Expand file tree
/
Copy pathportman.py
More file actions
239 lines (206 loc) · 7.33 KB
/
Copy pathportman.py
File metadata and controls
239 lines (206 loc) · 7.33 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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#!/usr/bin/env python3
"""
portman — Localhost port manager. Find and kill processes by port.
Cross-platform (Windows/Mac/Linux). No dependencies. No Node.js required.
Stop Googling "kill port 3000" forever.
Usage:
py portman.py # List all listening ports
py portman.py 3000 # Show what's on port 3000
py portman.py 3000 --kill # Kill process on port 3000
py portman.py 3000 8080 5432 # Check multiple ports
py portman.py --kill-all 3000 8080 # Kill multiple ports
py portman.py --filter node # Show only Node.js processes
"""
import argparse
import os
import platform
import re
import subprocess
import sys
def get_listening_ports_windows() -> list[dict]:
"""Get all listening ports on Windows using netstat."""
ports = []
try:
output = subprocess.check_output(
["netstat", "-ano", "-p", "TCP"],
text=True, stderr=subprocess.DEVNULL
)
except Exception:
return ports
for line in output.splitlines():
if "LISTENING" not in line:
continue
parts = line.split()
if len(parts) < 5:
continue
local_addr = parts[1]
pid = parts[4]
try:
port = int(local_addr.split(":")[-1])
pid = int(pid)
except (ValueError, IndexError):
continue
# Get process name
proc_name = get_process_name_windows(pid)
ports.append({
"port": port,
"pid": pid,
"process": proc_name,
"address": local_addr,
})
return ports
def get_process_name_windows(pid: int) -> str:
"""Get process name by PID on Windows."""
try:
output = subprocess.check_output(
["tasklist", "/FI", f"PID eq {pid}", "/FO", "CSV", "/NH"],
text=True, stderr=subprocess.DEVNULL
)
parts = output.strip().split(",")
if parts:
return parts[0].strip('"')
except Exception:
pass
return "unknown"
def get_listening_ports_unix() -> list[dict]:
"""Get all listening ports on Mac/Linux using lsof or ss."""
ports = []
# Try lsof first (works on Mac and most Linux)
try:
output = subprocess.check_output(
["lsof", "-iTCP", "-sTCP:LISTEN", "-nP"],
text=True, stderr=subprocess.DEVNULL
)
for line in output.splitlines()[1:]: # skip header
parts = line.split()
if len(parts) < 9:
continue
proc_name = parts[0]
pid = int(parts[1])
addr_port = parts[8]
try:
port = int(addr_port.split(":")[-1])
except (ValueError, IndexError):
continue
ports.append({
"port": port,
"pid": pid,
"process": proc_name,
"address": addr_port,
})
return ports
except (FileNotFoundError, subprocess.CalledProcessError):
pass
# Fallback to ss (Linux)
try:
output = subprocess.check_output(
["ss", "-tlnp"],
text=True, stderr=subprocess.DEVNULL
)
for line in output.splitlines()[1:]:
parts = line.split()
if len(parts) < 5:
continue
addr = parts[3]
try:
port = int(addr.split(":")[-1])
except (ValueError, IndexError):
continue
# Extract process info
proc_info = parts[-1] if len(parts) > 5 else ""
pid_match = re.search(r'pid=(\d+)', proc_info)
name_match = re.search(r'"([^"]+)"', proc_info)
pid = int(pid_match.group(1)) if pid_match else 0
proc_name = name_match.group(1) if name_match else "unknown"
ports.append({
"port": port,
"pid": pid,
"process": proc_name,
"address": addr,
})
return ports
except (FileNotFoundError, subprocess.CalledProcessError):
pass
return ports
def get_listening_ports() -> list[dict]:
"""Cross-platform port listing."""
if platform.system() == "Windows":
return get_listening_ports_windows()
else:
return get_listening_ports_unix()
def kill_process(pid: int) -> bool:
"""Kill a process by PID. Cross-platform."""
try:
if platform.system() == "Windows":
subprocess.check_call(
["taskkill", "/F", "/PID", str(pid)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
else:
os.kill(pid, 9) # SIGKILL
return True
except Exception:
return False
def format_port_table(ports: list[dict]) -> str:
"""Format port list as readable table."""
if not ports:
return " No listening ports found."
lines = []
lines.append(f" {'PORT':>6} {'PID':>7} {'PROCESS':<25} {'ADDRESS'}")
lines.append(f" {'-'*6} {'-'*7} {'-'*25} {'-'*20}")
for p in sorted(ports, key=lambda x: x["port"]):
lines.append(f" {p['port']:>6} {p['pid']:>7} {p['process']:<25} {p['address']}")
return "\n".join(lines)
def main():
parser = argparse.ArgumentParser(
description="portman -- find and kill processes by port"
)
parser.add_argument("ports", nargs="*", type=int, help="Port number(s) to check")
parser.add_argument("--kill", "-k", action="store_true", help="Kill process on specified port(s)")
parser.add_argument("--kill-all", action="store_true", help="Kill processes on ALL specified ports")
parser.add_argument("--filter", "-f", help="Filter by process name (substring match)")
args = parser.parse_args()
# Get all listening ports
all_ports = get_listening_ports()
# Deduplicate by port (keep first entry per port)
seen = set()
unique_ports = []
for p in all_ports:
if p["port"] not in seen:
seen.add(p["port"])
unique_ports.append(p)
all_ports = unique_ports
# Filter by specified ports
if args.ports:
target_ports = set(args.ports)
matched = [p for p in all_ports if p["port"] in target_ports]
unmatched = target_ports - {p["port"] for p in matched}
if args.kill or args.kill_all:
# Kill mode
for p in matched:
success = kill_process(p["pid"])
status = "killed" if success else "FAILED"
print(f" [{status:>6}] Port {p['port']} -- {p['process']} (PID {p['pid']})")
for port in unmatched:
print(f" [ free] Port {port} -- nothing running")
else:
# Info mode
print()
if matched:
print(format_port_table(matched))
for port in unmatched:
print(f" {port:>6} -- FREE (nothing listening)")
print()
elif args.filter:
# Filter by process name
filtered = [p for p in all_ports if args.filter.lower() in p["process"].lower()]
print(f"\n Processes matching '{args.filter}':\n")
print(format_port_table(filtered))
print()
else:
# List all
print(f"\n Listening ports ({len(all_ports)} total):\n")
print(format_port_table(all_ports))
print()
if __name__ == "__main__":
main()