27 lines
817 B
Python
27 lines
817 B
Python
import os
|
|
import psutil
|
|
import signal
|
|
|
|
|
|
def stop_server(port):
|
|
# 遍历当前所有运行的进程
|
|
for proc in psutil.process_iter(attrs=['pid', 'name']):
|
|
try:
|
|
# 查找进程监听的所有连接
|
|
for conn in proc.connections(kind='inet'):
|
|
if conn.laddr.port == port:
|
|
print(f"Killing process {proc.info['name']} (PID: {proc.info['pid']}) on port {port}")
|
|
os.kill(proc.info['pid'], signal.SIGTERM)
|
|
return True
|
|
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|
continue
|
|
return False
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
PORT = 59001
|
|
if stop_server(PORT):
|
|
print(f"Process on port {PORT} has been terminated.")
|
|
else:
|
|
print(f"No process found on port {PORT}.") |