portcheck-cli 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- portcheck_cli-0.1.0/LICENSE +21 -0
- portcheck_cli-0.1.0/PKG-INFO +114 -0
- portcheck_cli-0.1.0/README.md +85 -0
- portcheck_cli-0.1.0/portcheck/__init__.py +2 -0
- portcheck_cli-0.1.0/portcheck/cli.py +444 -0
- portcheck_cli-0.1.0/portcheck_cli.egg-info/PKG-INFO +114 -0
- portcheck_cli-0.1.0/portcheck_cli.egg-info/SOURCES.txt +11 -0
- portcheck_cli-0.1.0/portcheck_cli.egg-info/dependency_links.txt +1 -0
- portcheck_cli-0.1.0/portcheck_cli.egg-info/entry_points.txt +2 -0
- portcheck_cli-0.1.0/portcheck_cli.egg-info/requires.txt +2 -0
- portcheck_cli-0.1.0/portcheck_cli.egg-info/top_level.txt +1 -0
- portcheck_cli-0.1.0/pyproject.toml +45 -0
- portcheck_cli-0.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Marcus
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: portcheck-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Check what's using a port and optionally kill it
|
|
5
|
+
Author-email: Marcus <marcus.builds.things@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/marcusbuildsthings-droid/portcheck
|
|
8
|
+
Project-URL: Repository, https://github.com/marcusbuildsthings-droid/portcheck
|
|
9
|
+
Keywords: port,network,cli,process,kill,lsof
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: MacOS
|
|
15
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Topic :: System :: Networking
|
|
22
|
+
Classifier: Topic :: Utilities
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: click>=8.0
|
|
27
|
+
Requires-Dist: psutil>=5.9
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# portcheck
|
|
31
|
+
|
|
32
|
+
Check what's using a port and optionally kill it.
|
|
33
|
+
|
|
34
|
+
Simple, fast, with JSON output for automation.
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install portcheck-cli
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Usage
|
|
43
|
+
|
|
44
|
+
### Check a specific port
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
# See what's on port 8080
|
|
48
|
+
portcheck check 8080
|
|
49
|
+
|
|
50
|
+
# Kill whatever's using port 8080
|
|
51
|
+
portcheck check 8080 --kill
|
|
52
|
+
|
|
53
|
+
# Force kill without confirmation
|
|
54
|
+
portcheck check 8080 --kill -f -y
|
|
55
|
+
|
|
56
|
+
# Check UDP port
|
|
57
|
+
portcheck check 53 --udp
|
|
58
|
+
|
|
59
|
+
# Get JSON output
|
|
60
|
+
portcheck check 8080 --json
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Scan a range of ports
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
# Scan ports 8000-9000
|
|
67
|
+
portcheck scan 8000 9000
|
|
68
|
+
|
|
69
|
+
# Get JSON output
|
|
70
|
+
portcheck scan 3000 3100 --json
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### List all listening ports
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
portcheck list
|
|
77
|
+
|
|
78
|
+
# JSON output
|
|
79
|
+
portcheck list --json
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### Kill a process by PID
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
portcheck kill 12345
|
|
86
|
+
portcheck kill 12345 -f -y # Force, no confirm
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## JSON Output
|
|
90
|
+
|
|
91
|
+
All commands support `--json` for machine-readable output:
|
|
92
|
+
|
|
93
|
+
```json
|
|
94
|
+
[
|
|
95
|
+
{
|
|
96
|
+
"port": 8080,
|
|
97
|
+
"protocol": "TCP",
|
|
98
|
+
"status": "LISTEN",
|
|
99
|
+
"pid": 12345,
|
|
100
|
+
"local_address": "127.0.0.1:8080",
|
|
101
|
+
"name": "python",
|
|
102
|
+
"cmdline": "python -m http.server 8080",
|
|
103
|
+
"user": "ape"
|
|
104
|
+
}
|
|
105
|
+
]
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## For AI Agents
|
|
109
|
+
|
|
110
|
+
See [SKILL.md](SKILL.md) for agent-optimized documentation.
|
|
111
|
+
|
|
112
|
+
## License
|
|
113
|
+
|
|
114
|
+
MIT
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# portcheck
|
|
2
|
+
|
|
3
|
+
Check what's using a port and optionally kill it.
|
|
4
|
+
|
|
5
|
+
Simple, fast, with JSON output for automation.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install portcheck-cli
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
### Check a specific port
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
# See what's on port 8080
|
|
19
|
+
portcheck check 8080
|
|
20
|
+
|
|
21
|
+
# Kill whatever's using port 8080
|
|
22
|
+
portcheck check 8080 --kill
|
|
23
|
+
|
|
24
|
+
# Force kill without confirmation
|
|
25
|
+
portcheck check 8080 --kill -f -y
|
|
26
|
+
|
|
27
|
+
# Check UDP port
|
|
28
|
+
portcheck check 53 --udp
|
|
29
|
+
|
|
30
|
+
# Get JSON output
|
|
31
|
+
portcheck check 8080 --json
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Scan a range of ports
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
# Scan ports 8000-9000
|
|
38
|
+
portcheck scan 8000 9000
|
|
39
|
+
|
|
40
|
+
# Get JSON output
|
|
41
|
+
portcheck scan 3000 3100 --json
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### List all listening ports
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
portcheck list
|
|
48
|
+
|
|
49
|
+
# JSON output
|
|
50
|
+
portcheck list --json
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### Kill a process by PID
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
portcheck kill 12345
|
|
57
|
+
portcheck kill 12345 -f -y # Force, no confirm
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## JSON Output
|
|
61
|
+
|
|
62
|
+
All commands support `--json` for machine-readable output:
|
|
63
|
+
|
|
64
|
+
```json
|
|
65
|
+
[
|
|
66
|
+
{
|
|
67
|
+
"port": 8080,
|
|
68
|
+
"protocol": "TCP",
|
|
69
|
+
"status": "LISTEN",
|
|
70
|
+
"pid": 12345,
|
|
71
|
+
"local_address": "127.0.0.1:8080",
|
|
72
|
+
"name": "python",
|
|
73
|
+
"cmdline": "python -m http.server 8080",
|
|
74
|
+
"user": "ape"
|
|
75
|
+
}
|
|
76
|
+
]
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## For AI Agents
|
|
80
|
+
|
|
81
|
+
See [SKILL.md](SKILL.md) for agent-optimized documentation.
|
|
82
|
+
|
|
83
|
+
## License
|
|
84
|
+
|
|
85
|
+
MIT
|
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""portcheck - Check what's using a port and optionally kill it."""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import platform
|
|
7
|
+
import re
|
|
8
|
+
import signal
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
import click
|
|
14
|
+
import psutil
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def get_process_on_port_lsof(port: int, protocol: str = "tcp") -> list[dict]:
|
|
18
|
+
"""Use lsof to find processes on a port (macOS/Linux fallback)."""
|
|
19
|
+
results = []
|
|
20
|
+
proto_flag = "-iTCP" if protocol == "tcp" else "-iUDP"
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
output = subprocess.run(
|
|
24
|
+
["lsof", proto_flag + f":{port}", "-nP"],
|
|
25
|
+
capture_output=True,
|
|
26
|
+
text=True
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
for line in output.stdout.strip().split("\n")[1:]: # Skip header
|
|
30
|
+
if not line:
|
|
31
|
+
continue
|
|
32
|
+
|
|
33
|
+
parts = line.split()
|
|
34
|
+
if len(parts) >= 9:
|
|
35
|
+
proc_info = {
|
|
36
|
+
"port": port,
|
|
37
|
+
"protocol": protocol.upper(),
|
|
38
|
+
"name": parts[0],
|
|
39
|
+
"pid": int(parts[1]) if parts[1].isdigit() else None,
|
|
40
|
+
"user": parts[2],
|
|
41
|
+
"local_address": parts[8] if len(parts) > 8 else "",
|
|
42
|
+
"status": parts[9] if len(parts) > 9 else "LISTEN",
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
# Get cmdline if we have pid
|
|
46
|
+
if proc_info["pid"]:
|
|
47
|
+
try:
|
|
48
|
+
proc = psutil.Process(proc_info["pid"])
|
|
49
|
+
proc_info["cmdline"] = " ".join(proc.cmdline())
|
|
50
|
+
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
results.append(proc_info)
|
|
54
|
+
except FileNotFoundError:
|
|
55
|
+
pass # lsof not available
|
|
56
|
+
|
|
57
|
+
return results
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def get_process_on_port_psutil(port: int, protocol: str = "tcp") -> list[dict]:
|
|
61
|
+
"""Use psutil to find processes on a port."""
|
|
62
|
+
results = []
|
|
63
|
+
|
|
64
|
+
for conn in psutil.net_connections(kind=protocol):
|
|
65
|
+
if conn.laddr and conn.laddr.port == port:
|
|
66
|
+
proc_info = {
|
|
67
|
+
"port": port,
|
|
68
|
+
"protocol": protocol.upper(),
|
|
69
|
+
"status": conn.status,
|
|
70
|
+
"pid": conn.pid,
|
|
71
|
+
"local_address": f"{conn.laddr.ip}:{conn.laddr.port}",
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if conn.raddr:
|
|
75
|
+
proc_info["remote_address"] = f"{conn.raddr.ip}:{conn.raddr.port}"
|
|
76
|
+
|
|
77
|
+
if conn.pid:
|
|
78
|
+
try:
|
|
79
|
+
proc = psutil.Process(conn.pid)
|
|
80
|
+
proc_info["name"] = proc.name()
|
|
81
|
+
proc_info["cmdline"] = " ".join(proc.cmdline())
|
|
82
|
+
proc_info["user"] = proc.username()
|
|
83
|
+
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|
84
|
+
pass
|
|
85
|
+
|
|
86
|
+
results.append(proc_info)
|
|
87
|
+
|
|
88
|
+
return results
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def get_process_on_port(port: int, protocol: str = "tcp") -> list[dict]:
|
|
92
|
+
"""Find processes on a port. Uses lsof on macOS, psutil elsewhere."""
|
|
93
|
+
# Try lsof first on macOS (works without special permissions)
|
|
94
|
+
if platform.system() == "Darwin":
|
|
95
|
+
results = get_process_on_port_lsof(port, protocol)
|
|
96
|
+
if results:
|
|
97
|
+
return results
|
|
98
|
+
|
|
99
|
+
# Fall back to psutil
|
|
100
|
+
try:
|
|
101
|
+
return get_process_on_port_psutil(port, protocol)
|
|
102
|
+
except psutil.AccessDenied:
|
|
103
|
+
# On macOS, try lsof as last resort
|
|
104
|
+
return get_process_on_port_lsof(port, protocol)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def scan_ports_lsof(start: int, end: int, protocol: str = "tcp") -> list[dict]:
|
|
108
|
+
"""Scan port range using lsof."""
|
|
109
|
+
results = []
|
|
110
|
+
proto_flag = "-iTCP" if protocol == "tcp" else "-iUDP"
|
|
111
|
+
|
|
112
|
+
try:
|
|
113
|
+
output = subprocess.run(
|
|
114
|
+
["lsof", proto_flag, "-nP", "-sTCP:LISTEN"],
|
|
115
|
+
capture_output=True,
|
|
116
|
+
text=True
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
port_re = re.compile(r":(\d+)\s")
|
|
120
|
+
|
|
121
|
+
for line in output.stdout.strip().split("\n")[1:]:
|
|
122
|
+
if not line:
|
|
123
|
+
continue
|
|
124
|
+
|
|
125
|
+
match = port_re.search(line)
|
|
126
|
+
if match:
|
|
127
|
+
port = int(match.group(1))
|
|
128
|
+
if start <= port <= end:
|
|
129
|
+
parts = line.split()
|
|
130
|
+
if len(parts) >= 3:
|
|
131
|
+
results.append({
|
|
132
|
+
"port": port,
|
|
133
|
+
"protocol": protocol.upper(),
|
|
134
|
+
"name": parts[0],
|
|
135
|
+
"pid": int(parts[1]) if parts[1].isdigit() else None,
|
|
136
|
+
"user": parts[2],
|
|
137
|
+
"status": "LISTEN",
|
|
138
|
+
})
|
|
139
|
+
except FileNotFoundError:
|
|
140
|
+
pass
|
|
141
|
+
|
|
142
|
+
# Dedupe by port
|
|
143
|
+
seen = set()
|
|
144
|
+
deduped = []
|
|
145
|
+
for r in results:
|
|
146
|
+
if r["port"] not in seen:
|
|
147
|
+
seen.add(r["port"])
|
|
148
|
+
deduped.append(r)
|
|
149
|
+
|
|
150
|
+
return sorted(deduped, key=lambda x: x["port"])
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def scan_ports(start: int, end: int, protocol: str = "tcp") -> list[dict]:
|
|
154
|
+
"""Scan a range of ports for listeners."""
|
|
155
|
+
# Use lsof on macOS
|
|
156
|
+
if platform.system() == "Darwin":
|
|
157
|
+
results = scan_ports_lsof(start, end, protocol)
|
|
158
|
+
if results:
|
|
159
|
+
return results
|
|
160
|
+
|
|
161
|
+
# Fall back to psutil
|
|
162
|
+
results = []
|
|
163
|
+
seen_ports = set()
|
|
164
|
+
|
|
165
|
+
try:
|
|
166
|
+
for conn in psutil.net_connections(kind=protocol):
|
|
167
|
+
if conn.laddr and start <= conn.laddr.port <= end:
|
|
168
|
+
if conn.laddr.port not in seen_ports:
|
|
169
|
+
results.extend(get_process_on_port(conn.laddr.port, protocol))
|
|
170
|
+
seen_ports.add(conn.laddr.port)
|
|
171
|
+
except psutil.AccessDenied:
|
|
172
|
+
return scan_ports_lsof(start, end, protocol)
|
|
173
|
+
|
|
174
|
+
return sorted(results, key=lambda x: x["port"])
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def list_listening_lsof() -> list[dict]:
|
|
178
|
+
"""List all listening ports using lsof."""
|
|
179
|
+
results = []
|
|
180
|
+
|
|
181
|
+
try:
|
|
182
|
+
output = subprocess.run(
|
|
183
|
+
["lsof", "-iTCP", "-nP", "-sTCP:LISTEN"],
|
|
184
|
+
capture_output=True,
|
|
185
|
+
text=True
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
port_re = re.compile(r":(\d+)\s")
|
|
189
|
+
|
|
190
|
+
for line in output.stdout.strip().split("\n")[1:]:
|
|
191
|
+
if not line:
|
|
192
|
+
continue
|
|
193
|
+
|
|
194
|
+
match = port_re.search(line)
|
|
195
|
+
if match:
|
|
196
|
+
port = int(match.group(1))
|
|
197
|
+
parts = line.split()
|
|
198
|
+
if len(parts) >= 9:
|
|
199
|
+
addr_parts = parts[8].split(":")
|
|
200
|
+
address = addr_parts[0] if len(addr_parts) > 1 else "*"
|
|
201
|
+
|
|
202
|
+
results.append({
|
|
203
|
+
"port": port,
|
|
204
|
+
"address": address,
|
|
205
|
+
"pid": int(parts[1]) if parts[1].isdigit() else None,
|
|
206
|
+
"name": parts[0],
|
|
207
|
+
"user": parts[2],
|
|
208
|
+
})
|
|
209
|
+
except FileNotFoundError:
|
|
210
|
+
pass
|
|
211
|
+
|
|
212
|
+
# Dedupe
|
|
213
|
+
seen = set()
|
|
214
|
+
deduped = []
|
|
215
|
+
for r in results:
|
|
216
|
+
if r["port"] not in seen:
|
|
217
|
+
seen.add(r["port"])
|
|
218
|
+
deduped.append(r)
|
|
219
|
+
|
|
220
|
+
return sorted(deduped, key=lambda x: x["port"])
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def kill_process(pid: int, force: bool = False) -> bool:
|
|
224
|
+
"""Kill a process by PID."""
|
|
225
|
+
try:
|
|
226
|
+
proc = psutil.Process(pid)
|
|
227
|
+
if force:
|
|
228
|
+
proc.kill() # SIGKILL
|
|
229
|
+
else:
|
|
230
|
+
proc.terminate() # SIGTERM
|
|
231
|
+
return True
|
|
232
|
+
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|
233
|
+
# Try os.kill as fallback
|
|
234
|
+
try:
|
|
235
|
+
sig = signal.SIGKILL if force else signal.SIGTERM
|
|
236
|
+
os.kill(pid, sig)
|
|
237
|
+
return True
|
|
238
|
+
except (ProcessLookupError, PermissionError):
|
|
239
|
+
return False
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@click.group()
|
|
243
|
+
@click.version_option()
|
|
244
|
+
def main():
|
|
245
|
+
"""Check what's using a port and optionally kill it."""
|
|
246
|
+
pass
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
@main.command()
|
|
250
|
+
@click.argument("port", type=int)
|
|
251
|
+
@click.option("--udp", is_flag=True, help="Check UDP instead of TCP")
|
|
252
|
+
@click.option("--json", "as_json", is_flag=True, help="Output as JSON")
|
|
253
|
+
@click.option("--kill", "do_kill", is_flag=True, help="Kill the process using this port")
|
|
254
|
+
@click.option("-f", "--force", is_flag=True, help="Force kill (SIGKILL instead of SIGTERM)")
|
|
255
|
+
@click.option("-y", "--yes", is_flag=True, help="Don't prompt before killing")
|
|
256
|
+
def check(port: int, udp: bool, as_json: bool, do_kill: bool, force: bool, yes: bool):
|
|
257
|
+
"""Check what's using a specific port.
|
|
258
|
+
|
|
259
|
+
Examples:
|
|
260
|
+
portcheck check 8080
|
|
261
|
+
portcheck check 8080 --kill
|
|
262
|
+
portcheck check 8080 --kill -f -y
|
|
263
|
+
portcheck check 53 --udp
|
|
264
|
+
"""
|
|
265
|
+
protocol = "udp" if udp else "tcp"
|
|
266
|
+
results = get_process_on_port(port, protocol)
|
|
267
|
+
|
|
268
|
+
if as_json:
|
|
269
|
+
click.echo(json.dumps(results, indent=2, default=str))
|
|
270
|
+
return
|
|
271
|
+
|
|
272
|
+
if not results:
|
|
273
|
+
click.echo(f"Port {port}/{protocol.upper()} is free")
|
|
274
|
+
sys.exit(0)
|
|
275
|
+
|
|
276
|
+
for proc in results:
|
|
277
|
+
pid = proc.get("pid", "unknown")
|
|
278
|
+
name = proc.get("name", "unknown")
|
|
279
|
+
user = proc.get("user", "unknown")
|
|
280
|
+
status = proc.get("status", "unknown")
|
|
281
|
+
cmdline = proc.get("cmdline", "")
|
|
282
|
+
|
|
283
|
+
click.echo(f"Port {port}/{protocol.upper()} - {status}")
|
|
284
|
+
click.echo(f" PID: {pid}")
|
|
285
|
+
click.echo(f" Process: {name}")
|
|
286
|
+
click.echo(f" User: {user}")
|
|
287
|
+
if cmdline:
|
|
288
|
+
if len(cmdline) > 80:
|
|
289
|
+
cmdline = cmdline[:77] + "..."
|
|
290
|
+
click.echo(f" Command: {cmdline}")
|
|
291
|
+
|
|
292
|
+
if do_kill and pid and pid != "unknown":
|
|
293
|
+
if not yes:
|
|
294
|
+
if not click.confirm(f"Kill process {pid} ({name})?"):
|
|
295
|
+
continue
|
|
296
|
+
|
|
297
|
+
action = "Force killing" if force else "Terminating"
|
|
298
|
+
click.echo(f" {action} process {pid}...")
|
|
299
|
+
|
|
300
|
+
if kill_process(pid, force):
|
|
301
|
+
click.secho(f" ✓ Process {pid} killed", fg="green")
|
|
302
|
+
else:
|
|
303
|
+
click.secho(f" ✗ Failed to kill process {pid}", fg="red")
|
|
304
|
+
sys.exit(1)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
@main.command()
|
|
308
|
+
@click.argument("start", type=int)
|
|
309
|
+
@click.argument("end", type=int, required=False)
|
|
310
|
+
@click.option("--udp", is_flag=True, help="Scan UDP instead of TCP")
|
|
311
|
+
@click.option("--json", "as_json", is_flag=True, help="Output as JSON")
|
|
312
|
+
def scan(start: int, end: Optional[int], udp: bool, as_json: bool):
|
|
313
|
+
"""Scan a range of ports for listeners.
|
|
314
|
+
|
|
315
|
+
Examples:
|
|
316
|
+
portcheck scan 8000 9000
|
|
317
|
+
portcheck scan 3000 3100 --json
|
|
318
|
+
"""
|
|
319
|
+
if end is None:
|
|
320
|
+
end = start + 100
|
|
321
|
+
|
|
322
|
+
if start > end:
|
|
323
|
+
start, end = end, start
|
|
324
|
+
|
|
325
|
+
protocol = "udp" if udp else "tcp"
|
|
326
|
+
results = scan_ports(start, end, protocol)
|
|
327
|
+
|
|
328
|
+
if as_json:
|
|
329
|
+
click.echo(json.dumps(results, indent=2, default=str))
|
|
330
|
+
return
|
|
331
|
+
|
|
332
|
+
if not results:
|
|
333
|
+
click.echo(f"No listeners found on ports {start}-{end}/{protocol.upper()}")
|
|
334
|
+
return
|
|
335
|
+
|
|
336
|
+
click.echo(f"Listeners on ports {start}-{end}/{protocol.upper()}:")
|
|
337
|
+
click.echo()
|
|
338
|
+
|
|
339
|
+
for proc in results:
|
|
340
|
+
port = proc.get("port")
|
|
341
|
+
pid = proc.get("pid", "?")
|
|
342
|
+
name = proc.get("name", "unknown")
|
|
343
|
+
user = proc.get("user", "?")
|
|
344
|
+
|
|
345
|
+
click.echo(f" {port:5d} {name:<20} (PID: {pid}, User: {user})")
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
@main.command("list")
|
|
349
|
+
@click.option("--json", "as_json", is_flag=True, help="Output as JSON")
|
|
350
|
+
@click.option("--limit", type=int, default=50, help="Max results to show")
|
|
351
|
+
def list_cmd(as_json: bool, limit: int):
|
|
352
|
+
"""List all listening ports.
|
|
353
|
+
|
|
354
|
+
Examples:
|
|
355
|
+
portcheck list
|
|
356
|
+
portcheck list --json
|
|
357
|
+
"""
|
|
358
|
+
# Use lsof on macOS
|
|
359
|
+
if platform.system() == "Darwin":
|
|
360
|
+
results = list_listening_lsof()[:limit]
|
|
361
|
+
else:
|
|
362
|
+
results = []
|
|
363
|
+
seen = set()
|
|
364
|
+
|
|
365
|
+
try:
|
|
366
|
+
for conn in psutil.net_connections(kind="inet"):
|
|
367
|
+
if conn.status == "LISTEN" and conn.laddr:
|
|
368
|
+
if conn.laddr.port not in seen:
|
|
369
|
+
seen.add(conn.laddr.port)
|
|
370
|
+
proc_info = {
|
|
371
|
+
"port": conn.laddr.port,
|
|
372
|
+
"address": conn.laddr.ip,
|
|
373
|
+
"pid": conn.pid,
|
|
374
|
+
}
|
|
375
|
+
if conn.pid:
|
|
376
|
+
try:
|
|
377
|
+
proc = psutil.Process(conn.pid)
|
|
378
|
+
proc_info["name"] = proc.name()
|
|
379
|
+
proc_info["user"] = proc.username()
|
|
380
|
+
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|
381
|
+
pass
|
|
382
|
+
results.append(proc_info)
|
|
383
|
+
except psutil.AccessDenied:
|
|
384
|
+
results = list_listening_lsof()
|
|
385
|
+
|
|
386
|
+
results = sorted(results, key=lambda x: x["port"])[:limit]
|
|
387
|
+
|
|
388
|
+
if as_json:
|
|
389
|
+
click.echo(json.dumps(results, indent=2, default=str))
|
|
390
|
+
return
|
|
391
|
+
|
|
392
|
+
if not results:
|
|
393
|
+
click.echo("No listening ports found")
|
|
394
|
+
return
|
|
395
|
+
|
|
396
|
+
click.echo(f"{'PORT':<7} {'ADDRESS':<16} {'PID':<8} {'PROCESS':<20} {'USER'}")
|
|
397
|
+
click.echo("-" * 65)
|
|
398
|
+
|
|
399
|
+
for r in results:
|
|
400
|
+
port = r.get("port", "?")
|
|
401
|
+
addr = r.get("address", "*")
|
|
402
|
+
pid = r.get("pid", "?")
|
|
403
|
+
name = r.get("name", "?")[:20] if r.get("name") else "?"
|
|
404
|
+
user = r.get("user", "?")
|
|
405
|
+
|
|
406
|
+
click.echo(f"{port:<7} {addr:<16} {pid:<8} {name:<20} {user}")
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
@main.command()
|
|
410
|
+
@click.argument("pid", type=int)
|
|
411
|
+
@click.option("-f", "--force", is_flag=True, help="Force kill (SIGKILL)")
|
|
412
|
+
@click.option("-y", "--yes", is_flag=True, help="Don't prompt")
|
|
413
|
+
def kill(pid: int, force: bool, yes: bool):
|
|
414
|
+
"""Kill a process by PID.
|
|
415
|
+
|
|
416
|
+
Examples:
|
|
417
|
+
portcheck kill 12345
|
|
418
|
+
portcheck kill 12345 -f -y
|
|
419
|
+
"""
|
|
420
|
+
try:
|
|
421
|
+
proc = psutil.Process(pid)
|
|
422
|
+
name = proc.name()
|
|
423
|
+
except psutil.NoSuchProcess:
|
|
424
|
+
click.secho(f"No process with PID {pid}", fg="red")
|
|
425
|
+
sys.exit(1)
|
|
426
|
+
except psutil.AccessDenied:
|
|
427
|
+
name = "unknown"
|
|
428
|
+
|
|
429
|
+
if not yes:
|
|
430
|
+
if not click.confirm(f"Kill process {pid} ({name})?"):
|
|
431
|
+
sys.exit(0)
|
|
432
|
+
|
|
433
|
+
action = "Force killing" if force else "Terminating"
|
|
434
|
+
click.echo(f"{action} process {pid} ({name})...")
|
|
435
|
+
|
|
436
|
+
if kill_process(pid, force):
|
|
437
|
+
click.secho(f"✓ Process {pid} killed", fg="green")
|
|
438
|
+
else:
|
|
439
|
+
click.secho(f"✗ Failed to kill process {pid}", fg="red")
|
|
440
|
+
sys.exit(1)
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
if __name__ == "__main__":
|
|
444
|
+
main()
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: portcheck-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Check what's using a port and optionally kill it
|
|
5
|
+
Author-email: Marcus <marcus.builds.things@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/marcusbuildsthings-droid/portcheck
|
|
8
|
+
Project-URL: Repository, https://github.com/marcusbuildsthings-droid/portcheck
|
|
9
|
+
Keywords: port,network,cli,process,kill,lsof
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: MacOS
|
|
15
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Topic :: System :: Networking
|
|
22
|
+
Classifier: Topic :: Utilities
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: click>=8.0
|
|
27
|
+
Requires-Dist: psutil>=5.9
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# portcheck
|
|
31
|
+
|
|
32
|
+
Check what's using a port and optionally kill it.
|
|
33
|
+
|
|
34
|
+
Simple, fast, with JSON output for automation.
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install portcheck-cli
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Usage
|
|
43
|
+
|
|
44
|
+
### Check a specific port
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
# See what's on port 8080
|
|
48
|
+
portcheck check 8080
|
|
49
|
+
|
|
50
|
+
# Kill whatever's using port 8080
|
|
51
|
+
portcheck check 8080 --kill
|
|
52
|
+
|
|
53
|
+
# Force kill without confirmation
|
|
54
|
+
portcheck check 8080 --kill -f -y
|
|
55
|
+
|
|
56
|
+
# Check UDP port
|
|
57
|
+
portcheck check 53 --udp
|
|
58
|
+
|
|
59
|
+
# Get JSON output
|
|
60
|
+
portcheck check 8080 --json
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Scan a range of ports
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
# Scan ports 8000-9000
|
|
67
|
+
portcheck scan 8000 9000
|
|
68
|
+
|
|
69
|
+
# Get JSON output
|
|
70
|
+
portcheck scan 3000 3100 --json
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### List all listening ports
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
portcheck list
|
|
77
|
+
|
|
78
|
+
# JSON output
|
|
79
|
+
portcheck list --json
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### Kill a process by PID
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
portcheck kill 12345
|
|
86
|
+
portcheck kill 12345 -f -y # Force, no confirm
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## JSON Output
|
|
90
|
+
|
|
91
|
+
All commands support `--json` for machine-readable output:
|
|
92
|
+
|
|
93
|
+
```json
|
|
94
|
+
[
|
|
95
|
+
{
|
|
96
|
+
"port": 8080,
|
|
97
|
+
"protocol": "TCP",
|
|
98
|
+
"status": "LISTEN",
|
|
99
|
+
"pid": 12345,
|
|
100
|
+
"local_address": "127.0.0.1:8080",
|
|
101
|
+
"name": "python",
|
|
102
|
+
"cmdline": "python -m http.server 8080",
|
|
103
|
+
"user": "ape"
|
|
104
|
+
}
|
|
105
|
+
]
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## For AI Agents
|
|
109
|
+
|
|
110
|
+
See [SKILL.md](SKILL.md) for agent-optimized documentation.
|
|
111
|
+
|
|
112
|
+
## License
|
|
113
|
+
|
|
114
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
portcheck/__init__.py
|
|
5
|
+
portcheck/cli.py
|
|
6
|
+
portcheck_cli.egg-info/PKG-INFO
|
|
7
|
+
portcheck_cli.egg-info/SOURCES.txt
|
|
8
|
+
portcheck_cli.egg-info/dependency_links.txt
|
|
9
|
+
portcheck_cli.egg-info/entry_points.txt
|
|
10
|
+
portcheck_cli.egg-info/requires.txt
|
|
11
|
+
portcheck_cli.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
portcheck
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "portcheck-cli"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Check what's using a port and optionally kill it"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = {text = "MIT"}
|
|
11
|
+
authors = [
|
|
12
|
+
{name = "Marcus", email = "marcus.builds.things@gmail.com"}
|
|
13
|
+
]
|
|
14
|
+
keywords = ["port", "network", "cli", "process", "kill", "lsof"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Environment :: Console",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"License :: OSI Approved :: MIT License",
|
|
20
|
+
"Operating System :: MacOS",
|
|
21
|
+
"Operating System :: POSIX :: Linux",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3.9",
|
|
24
|
+
"Programming Language :: Python :: 3.10",
|
|
25
|
+
"Programming Language :: Python :: 3.11",
|
|
26
|
+
"Programming Language :: Python :: 3.12",
|
|
27
|
+
"Topic :: System :: Networking",
|
|
28
|
+
"Topic :: Utilities",
|
|
29
|
+
]
|
|
30
|
+
requires-python = ">=3.9"
|
|
31
|
+
dependencies = [
|
|
32
|
+
"click>=8.0",
|
|
33
|
+
"psutil>=5.9",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[project.urls]
|
|
37
|
+
Homepage = "https://github.com/marcusbuildsthings-droid/portcheck"
|
|
38
|
+
Repository = "https://github.com/marcusbuildsthings-droid/portcheck"
|
|
39
|
+
|
|
40
|
+
[project.scripts]
|
|
41
|
+
portcheck = "portcheck.cli:main"
|
|
42
|
+
|
|
43
|
+
[tool.setuptools.packages.find]
|
|
44
|
+
where = ["."]
|
|
45
|
+
include = ["portcheck*"]
|