欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > Python 端口进程管理工具

Python 端口进程管理工具

2025/11/10 11:10:23 来源:https://blog.csdn.net/Clay_K/article/details/145039866  浏览:    关键词:Python 端口进程管理工具

Python 端口进程管理工具

相关资源文件已经打包成EXE文件,可双击直接运行程序,且文章末尾已附上相关源码,以供大家学习交流,博主主页还有更多Python相关程序案例,秉着开源精神的想法,望大家喜欢,点个关注不迷路!!!

1. 简介:

这是我用python写的一个用于端口管理和进程管理的GUI工具,它可以显示当前系统上所有开放的端口信息,并且允许用户对选中的进程进行操作(如结束进程、定位进程文件夹路径、复制相关信息到剪贴板等)。

具体的功能包括:

  • 获取系统的开放端口信息,包括端口号、进程名称、协议类型(TCP/UDP)和进程路径。
  • 支持端口号、进程名称、PID的搜索。
  • 提供右键菜单,可以执行结束进程、定位进程路径、复制信息等操作。
  • 支持表格视图的滚动,可以查看大量端口数据。
  • 支持数据刷新,更新显示系统当前开放的端口和进程。

关键功能解析

  • 获取本机开放的端口信息:
  • 使用 psutil.net_connections(kind=‘inet’) 获取当前的网络连接信息,筛选出状态为 LISTEN
    的连接(即开放的端口)。
  • 获取与端口相关的进程信息,包括 PID、进程名称、进程路径等。

搜索功能:

  • 可以通过端口号、进程名称或 PID 搜索对应的端口和进程。
  • 用户可以输入查询的内容,选择查询的类型,点击查询按钮后,展示匹配的端口信息。

右键菜单:

右键点击某一行端口数据时,会弹出一个菜单,菜单中包含结束进程、定位进程文件夹路径、复制信息等选项。
结束进程:通过 psutil.Process(pid).terminate() 来结束选中的进程。
定位进程文件夹路径:使用 os.startfile() 打开进程所在的文件夹。
复制到剪贴板:使用 pyperclip.copy() 将选中的信息复制到系统剪贴板。
UI界面:

使用 ttk.Treeview 控件显示端口信息表格,支持垂直和水平滚动条。
创建了输入框和下拉菜单,供用户选择查询类型并输入查询内容。
界面功能
端口表格显示:

显示端口的详细信息,包括 PID、协议类型(TCP/UDP)、端口号、进程名称和路径。
支持垂直和水平滚动条,方便查看长列表。

查询功能:

  • 支持通过端口号、进程名称、PID查询端口信息。
  • 提供搜索框和下拉选择框,方便用户选择查询类型。

右键菜单操作:

  • 提供“结束进程”、“定位进程文件夹路径”、“复制信息”等选项。 刷新功能:
  • 点击刷新按钮可以重新加载端口信息,确保数据是最新的。

2. 运行效果:

在这里插入图片描述
在这里插入图片描述

3. 相关源码:

import tkinter as tk
from tkinter import ttk, messagebox
import psutil
import os
import pyperclip  # 引入pyperclip模块用于复制到剪贴板# 获取本机所有开放的端口及对应的进程信息
def get_open_ports():open_ports = []for conn in psutil.net_connections(kind='inet'):if conn.status != 'LISTEN':continuepid = conn.pidif conn.type == 1:  # TCP协议protocol = 'TCP'elif conn.type == 2:  # UDP协议protocol = 'UDP'else:protocol = 'N/A'try:process = psutil.Process(pid)process_name = process.name()exe_path = process.exe()except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):process_name = "N/A"exe_path = "N/A"open_ports.append({'Port': conn.laddr.port,'PID': pid,'Process Name': process_name,'Protocol': protocol,'Path': exe_path})return open_ports# 根据端口号查询对应进程的信息
def search_by_port(port):open_ports = get_open_ports()for port_info in open_ports:if port_info['Port'] == port:return port_inforeturn None# 根据进程名称查询对应的端口信息
def search_by_process_name(name):open_ports = get_open_ports()result = []for port_info in open_ports:if name.lower() in port_info['Process Name'].lower():result.append(port_info)return result# 根据PID查询对应的端口信息
def search_by_pid(pid):open_ports = get_open_ports()for port_info in open_ports:if port_info['PID'] == pid:return port_inforeturn None# 更新UI中的端口列表
def update_port_list():for row in treeview.get_children():treeview.delete(row)open_ports = get_open_ports()if not open_ports:messagebox.showinfo("没有找到端口", "没有开放的端口或无法获取端口信息。")returnfor port_info in open_ports:treeview.insert('', 'end', values=(port_info['PID'], port_info['Protocol'], port_info['Port'], port_info['Process Name'], port_info['Path']))# 根据选择的搜索类型执行相应的搜索
def search_selected_item():selected_type = combobox_search_type.get()search_value = entry_search_value.get()# 清空列表for row in treeview.get_children():treeview.delete(row)if selected_type == "端口号":try:port = int(search_value)port_info = search_by_port(port)if port_info:treeview.insert('', 'end', values=(port_info['PID'], port_info['Protocol'], port_info['Port'], port_info['Process Name'], port_info['Path']))else:messagebox.showinfo("未找到", f"未找到端口 {port} 对应的进程。")except ValueError:messagebox.showerror("输入错误", "请输入有效的端口号。")elif selected_type == "进程名称":result = search_by_process_name(search_value)if result:for port_info in result:treeview.insert('', 'end', values=(port_info['PID'], port_info['Protocol'], port_info['Port'], port_info['Process Name'], port_info['Path']))else:messagebox.showinfo("未找到", f"未找到进程名称包含 {search_value} 的记录。")elif selected_type == "PID":try:pid = int(search_value)port_info = search_by_pid(pid)if port_info:treeview.insert('', 'end', values=(port_info['PID'], port_info['Protocol'], port_info['Port'], port_info['Process Name'], port_info['Path']))else:messagebox.showinfo("未找到", f"未找到PID {pid} 对应的进程。")except ValueError:messagebox.showerror("输入错误", "请输入有效的PID。")# 结束进程
def kill_process(pid):try:process = psutil.Process(pid)process.terminate()  # 发送 terminate 信号process.wait()  # 等待进程结束messagebox.showinfo("结束进程", f"进程 (PID: {pid}) 已被成功结束。")except (psutil.NoSuchProcess, psutil.AccessDenied):messagebox.showerror("错误", "无法结束该进程,可能没有权限。")# 定位进程文件夹路径
def open_process_folder(exe_path):if exe_path and os.path.exists(exe_path):folder_path = os.path.dirname(exe_path)os.startfile(folder_path)  # 打开文件夹else:messagebox.showerror("错误", "无法找到进程文件路径。")# 复制到剪贴板的功能
def copy_to_clipboard(text):pyperclip.copy(text)  # 使用 pyperclip 库复制文本messagebox.showinfo("复制成功", "内容已复制到剪贴板")# 添加右键菜单
def on_right_click(event):selected_item = treeview.selection()if selected_item:pid = treeview.item(selected_item)['values'][0]  # 获取PID(现在第一列是PID)port = treeview.item(selected_item)['values'][2]  # 获取端口process_name = treeview.item(selected_item)['values'][3]  # 获取进程名称exe_path = treeview.item(selected_item)['values'][4]  # 获取路径menu = tk.Menu(root, tearoff=0)menu.add_command(label="结束进程", command=lambda: kill_process(int(pid)))menu.add_command(label="定位进程文件夹路径", command=lambda: open_process_folder(exe_path))menu.add_command(label="复制PID", command=lambda: copy_to_clipboard(pid))menu.add_command(label="复制端口号", command=lambda: copy_to_clipboard(port))menu.add_command(label="复制进程名称", command=lambda: copy_to_clipboard(process_name))menu.add_command(label="复制相关路径", command=lambda: copy_to_clipboard(exe_path))menu.post(event.x_root, event.y_root)# 创建GUI界面
root = tk.Tk()
root.title("端口进程管理工具")  # 更新窗口标题
root.geometry("968x699")# 创建并配置表格
columns = ("PID", "协议", "端口", "进程名称", "相关路径")  # 更新列顺序
treeview = ttk.Treeview(root, columns=columns, show='headings', height=25)
treeview.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)# 设置表头并使内容居中显示
for col in columns:treeview.heading(col, text=col)if col in ["PID", "协议", "端口"]:  # 设置PID、协议、端口列的宽度为固定10treeview.column(col, width=10, anchor='center')else:  # 其他列自动扩展treeview.column(col, anchor='center')# 创建滚动条
scrollbar_y = ttk.Scrollbar(root, orient="vertical", command=treeview.yview)
scrollbar_y.pack(side="right", fill="y")
treeview.configure(yscrollcommand=scrollbar_y.set)scrollbar_x = ttk.Scrollbar(root, orient="horizontal", command=treeview.xview)
scrollbar_x.pack(side="bottom", fill="x")
treeview.configure(xscrollcommand=scrollbar_x.set)# 创建搜索框和按钮
frame_search = tk.Frame(root)
frame_search.pack(pady=10, fill=tk.X)# 下拉选择框 - 选择搜索类型
label_search_type = tk.Label(frame_search, text="选择搜索类型:")
label_search_type.pack(side=tk.LEFT, padx=5)
combobox_search_type = ttk.Combobox(frame_search, values=["端口号", "进程名称", "PID"], width=15)
combobox_search_type.pack(side=tk.LEFT, padx=5)
combobox_search_type.set("端口号")  # 设置默认选项# 输入框 - 根据选择的搜索类型输入相应内容
label_search_value = tk.Label(frame_search, text="输入查询内容:")
label_search_value.pack(side=tk.LEFT, padx=5)
entry_search_value = tk.Entry(frame_search, width=20)
entry_search_value.pack(side=tk.LEFT, padx=5)# 查询按钮 - 设置不同尺寸
search_button = tk.Button(frame_search, text="查  询", width=18, height=1, command=search_selected_item)
search_button.pack(side=tk.LEFT, padx=15)# 刷新按钮 - 设置不同尺寸
refresh_button = tk.Button(frame_search, text="刷新列表", width=18, height=1, command=update_port_list)
refresh_button.pack(side=tk.RIGHT, padx=15, expand=True)# 初始化时更新端口信息
update_port_list()# 绑定右键菜单
treeview.bind("<Button-3>", on_right_click)root.mainloop()

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词