python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python端口进程管理工具

基于Python编写端口进程管理工具

作者:黑客白泽

这篇文章主要为大家介绍了如何使用Python编写一个用于端口管理和进程管理的GUI工具,它可以显示当前系统上所有开放的端口信息,感兴趣的可以了解下

1. 简介

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

具体的功能包括:

关键功能解析

搜索功能:

右键菜单:

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':
            continue
        
        pid = conn.pid
        if 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_info
    return 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_info
    return 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("没有找到端口", "没有开放的端口或无法获取端口信息。")
        return
    
    for 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、协议、端口列的宽度为固定10
        treeview.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()

以上就是基于Python编写端口进程管理工具的详细内容,更多关于Python端口进程管理工具的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文