#!encoding=utf8
'''
安装
pip install psutil
资料
https://github.com/giampaolo/psutil
https://psutil.readthedocs.io/en/latest/
'''
import psutil
import ctypes
import inspect
def kill_process(pid):
'''
根据父进程pid杀死进程及子进程
'''
print(f'终止进程号 {pid} 及所有子进程')
parent_proc = psutil.Process(pid)
# recursive = True 递归查找
for child_proc in parent_proc.children(recursive=True):
child_proc.kill()
parent_proc.kill()
def get_thread_ids(pid):
'''
根据PID 获取进程下所有线程id
return 线程ID列表
'''
p = psutil.Process(pid)
# 获取当前进程下所有线程
threads_list = p.threads()
tid_list = [t.id for t in threads_list]
return tid_list
def get_process_id_by_port(port):
'''
根据端口号获取目标进程ID
'''
for proc in psutil.process_iter():
# print (proc)
for c in proc.connections():
if c.status == psutil.CONN_LISTEN:
if c.laddr.port == int(port):
print(f'port: {c.laddr.port} ; pid : {proc.pid}')
print(proc)
return proc.pid
return None
def kill_process_by_port(port):
'''
根据端口号杀进程及子进程
'''
pid = get_process_id_by_port(port)
if pid:
print(f'找到端口号为 {port} 的进程, 正在终止进程及子进程')
kill_process(pid)
else:
print(f'未找到端口号为 {port} 的进程')
def stop_thread_by_tid(tid):
"""根据线程ID结束线程
tid: 线程ID
"""
exctype = SystemExit
print(f"开始结束线程 {tid}")
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
tid, ctypes.py_object(exctype))
if res == 1:
print("结束线程成功")
elif res == 0:
print("未找到线程id")
else:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
print("PyThreadState_SetAsyncExc failed")
if __name__=='__main__':
kill_process_by_port(8190)