-
Notifications
You must be signed in to change notification settings - Fork 1
/
killport.py
62 lines (44 loc) · 1.55 KB
/
killport.py
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
from __future__ import annotations
import argparse
from typing import NamedTuple
import psutil
class ProcessInfo(NamedTuple):
port: int
process: psutil.Process
def get_processes(ports: list[int]) -> list[ProcessInfo]:
processes = set()
for process in psutil.process_iter():
try:
conns = process.connections(kind='inet')
except (psutil.AccessDenied, psutil.ZombieProcess):
continue
for conn in conns:
port = conn.laddr.port
if port in ports:
processes.add(ProcessInfo(port=port, process=process))
return sorted(processes, key=lambda p: p.port)
def kill_ports(*, ports: list[int], view_only: bool = False) -> int:
if not ports:
print('Please supply a list of ports to kill')
return 1
processes = get_processes(ports)
if processes:
print('Killing:' if not view_only else 'Would kill:')
for pinfo in processes:
emoji = '⚠️ ' if view_only else '❌'
process = pinfo.process
print(
f'{emoji} {process.name()} (pid {process.pid}) '
f'on port {pinfo.port}',
)
if not view_only:
process.kill()
return 1 if processes else 0
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument('ports', type=int, nargs='*')
parser.add_argument('--view-only', action='store_true')
args = parser.parse_args()
return kill_ports(ports=args.ports, view_only=args.view_only)
if __name__ == '__main__':
raise SystemExit(main())