欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于Python編寫(xiě)端口進(jìn)程管理工具

 更新時(shí)間:2025年01月10日 08:40:44   作者:黑客白澤  
這篇文章主要為大家介紹了如何使用Python編寫(xiě)一個(gè)用于端口管理和進(jìn)程管理的GUI工具,它可以顯示當(dāng)前系統(tǒng)上所有開(kāi)放的端口信息,感興趣的可以了解下

1. 簡(jiǎn)介

這是我用python寫(xiě)的一個(gè)用于端口管理和進(jìn)程管理的GUI工具,它可以顯示當(dāng)前系統(tǒng)上所有開(kāi)放的端口信息,并且允許用戶對(duì)選中的進(jìn)程進(jìn)行操作(如結(jié)束進(jìn)程、定位進(jìn)程文件夾路徑、復(fù)制相關(guān)信息到剪貼板等)。

具體的功能包括:

  • 獲取系統(tǒng)的開(kāi)放端口信息,包括端口號(hào)、進(jìn)程名稱、協(xié)議類型(TCP/UDP)和進(jìn)程路徑。
  • 支持端口號(hào)、進(jìn)程名稱、PID的搜索。
  • 提供右鍵菜單,可以執(zhí)行結(jié)束進(jìn)程、定位進(jìn)程路徑、復(fù)制信息等操作。
  • 支持表格視圖的滾動(dòng),可以查看大量端口數(shù)據(jù)。
  • 支持?jǐn)?shù)據(jù)刷新,更新顯示系統(tǒng)當(dāng)前開(kāi)放的端口和進(jìn)程。

關(guān)鍵功能解析

  • 獲取本機(jī)開(kāi)放的端口信息:
  • 使用 psutil.net_connections(kind=‘inet’) 獲取當(dāng)前的網(wǎng)絡(luò)連接信息,篩選出狀態(tài)為 LISTEN的連接(即開(kāi)放的端口)。
  • 獲取與端口相關(guān)的進(jìn)程信息,包括 PID、進(jìn)程名稱、進(jìn)程路徑等。

搜索功能:

  • 可以通過(guò)端口號(hào)、進(jìn)程名稱或 PID 搜索對(duì)應(yīng)的端口和進(jìn)程。
  • 用戶可以輸入查詢的內(nèi)容,選擇查詢的類型,點(diǎn)擊查詢按鈕后,展示匹配的端口信息。

右鍵菜單:

  • 右鍵點(diǎn)擊某一行端口數(shù)據(jù)時(shí),會(huì)彈出一個(gè)菜單,菜單中包含結(jié)束進(jìn)程、定位進(jìn)程文件夾路徑、復(fù)制信息等選項(xiàng)。
  • 結(jié)束進(jìn)程:通過(guò) psutil.Process(pid).terminate() 來(lái)結(jié)束選中的進(jìn)程。
  • 定位進(jìn)程文件夾路徑:使用 os.startfile() 打開(kāi)進(jìn)程所在的文件夾。
  • 復(fù)制到剪貼板:使用 pyperclip.copy() 將選中的信息復(fù)制到系統(tǒng)剪貼板。

UI界面:

使用 ttk.Treeview 控件顯示端口信息表格,支持垂直和水平滾動(dòng)條。

創(chuàng)建了輸入框和下拉菜單,供用戶選擇查詢類型并輸入查詢內(nèi)容。

界面功能

端口表格顯示:

顯示端口的詳細(xì)信息,包括 PID、協(xié)議類型(TCP/UDP)、端口號(hào)、進(jìn)程名稱和路徑。

支持垂直和水平滾動(dòng)條,方便查看長(zhǎng)列表。

查詢功能:

支持通過(guò)端口號(hào)、進(jìn)程名稱、PID查詢端口信息。

提供搜索框和下拉選擇框,方便用戶選擇查詢類型。

右鍵菜單操作:

提供“結(jié)束進(jìn)程”、“定位進(jìn)程文件夾路徑”、“復(fù)制信息”等選項(xiàng)。 刷新功能:

點(diǎn)擊刷新按鈕可以重新加載端口信息,確保數(shù)據(jù)是最新的。

2. 運(yùn)行效果

3. 相關(guān)源碼

import tkinter as tk
from tkinter import ttk, messagebox
import psutil
import os
import pyperclip  # 引入pyperclip模塊用于復(fù)制到剪貼板

# 獲取本機(jī)所有開(kāi)放的端口及對(duì)應(yīng)的進(jìn)程信息
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協(xié)議
            protocol = 'TCP'
        elif conn.type == 2:  # UDP協(xié)議
            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

# 根據(jù)端口號(hào)查詢對(duì)應(yīng)進(jìn)程的信息
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

# 根據(jù)進(jìn)程名稱查詢對(duì)應(yīng)的端口信息
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

# 根據(jù)PID查詢對(duì)應(yīng)的端口信息
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("沒(méi)有找到端口", "沒(méi)有開(kāi)放的端口或無(wú)法獲取端口信息。")
        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']))

# 根據(jù)選擇的搜索類型執(zhí)行相應(yīng)的搜索
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 == "端口號(hào)":
        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} 對(duì)應(yīng)的進(jìn)程。")
        except ValueError:
            messagebox.showerror("輸入錯(cuò)誤", "請(qǐng)輸入有效的端口號(hào)。")
    elif selected_type == "進(jìn)程名稱":
        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"未找到進(jìn)程名稱包含 {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} 對(duì)應(yīng)的進(jìn)程。")
        except ValueError:
            messagebox.showerror("輸入錯(cuò)誤", "請(qǐng)輸入有效的PID。")

# 結(jié)束進(jìn)程
def kill_process(pid):
    try:
        process = psutil.Process(pid)
        process.terminate()  # 發(fā)送 terminate 信號(hào)
        process.wait()  # 等待進(jìn)程結(jié)束
        messagebox.showinfo("結(jié)束進(jìn)程", f"進(jìn)程 (PID: {pid}) 已被成功結(jié)束。")
    except (psutil.NoSuchProcess, psutil.AccessDenied):
        messagebox.showerror("錯(cuò)誤", "無(wú)法結(jié)束該進(jìn)程,可能沒(méi)有權(quán)限。")

# 定位進(jìn)程文件夾路徑
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)  # 打開(kāi)文件夾
    else:
        messagebox.showerror("錯(cuò)誤", "無(wú)法找到進(jìn)程文件路徑。")

# 復(fù)制到剪貼板的功能
def copy_to_clipboard(text):
    pyperclip.copy(text)  # 使用 pyperclip 庫(kù)復(fù)制文本
    messagebox.showinfo("復(fù)制成功", "內(nèi)容已復(fù)制到剪貼板")

# 添加右鍵菜單
def on_right_click(event):
    selected_item = treeview.selection()
    if selected_item:
        pid = treeview.item(selected_item)['values'][0]  # 獲取PID(現(xiàn)在第一列是PID)
        port = treeview.item(selected_item)['values'][2]  # 獲取端口
        process_name = treeview.item(selected_item)['values'][3]  # 獲取進(jìn)程名稱
        exe_path = treeview.item(selected_item)['values'][4]  # 獲取路徑
        menu = tk.Menu(root, tearoff=0)
        menu.add_command(label="結(jié)束進(jìn)程", command=lambda: kill_process(int(pid)))
        menu.add_command(label="定位進(jìn)程文件夾路徑", command=lambda: open_process_folder(exe_path))
        menu.add_command(label="復(fù)制PID", command=lambda: copy_to_clipboard(pid))
        menu.add_command(label="復(fù)制端口號(hào)", command=lambda: copy_to_clipboard(port))
        menu.add_command(label="復(fù)制進(jìn)程名稱", command=lambda: copy_to_clipboard(process_name))
        menu.add_command(label="復(fù)制相關(guān)路徑", command=lambda: copy_to_clipboard(exe_path))
        menu.post(event.x_root, event.y_root)

# 創(chuàng)建GUI界面
root = tk.Tk()
root.title("端口進(jìn)程管理工具")  # 更新窗口標(biāo)題
root.geometry("968x699")

# 創(chuàng)建并配置表格
columns = ("PID", "協(xié)議", "端口", "進(jìn)程名稱", "相關(guān)路徑")  # 更新列順序
treeview = ttk.Treeview(root, columns=columns, show='headings', height=25)
treeview.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

# 設(shè)置表頭并使內(nèi)容居中顯示
for col in columns:
    treeview.heading(col, text=col)
    if col in ["PID", "協(xié)議", "端口"]:  # 設(shè)置PID、協(xié)議、端口列的寬度為固定10
        treeview.column(col, width=10, anchor='center')
    else:  # 其他列自動(dòng)擴(kuò)展
        treeview.column(col, anchor='center')

# 創(chuàng)建滾動(dòng)條
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)

# 創(chuàng)建搜索框和按鈕
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=["端口號(hào)", "進(jìn)程名稱", "PID"], width=15)
combobox_search_type.pack(side=tk.LEFT, padx=5)
combobox_search_type.set("端口號(hào)")  # 設(shè)置默認(rèn)選項(xiàng)

# 輸入框 - 根據(jù)選擇的搜索類型輸入相應(yīng)內(nèi)容
label_search_value = tk.Label(frame_search, text="輸入查詢內(nèi)容:")
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)

# 查詢按鈕 - 設(shè)置不同尺寸
search_button = tk.Button(frame_search, text="查  詢", width=18, height=1, command=search_selected_item)
search_button.pack(side=tk.LEFT, padx=15)

# 刷新按鈕 - 設(shè)置不同尺寸
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)

# 初始化時(shí)更新端口信息
update_port_list()

# 綁定右鍵菜單
treeview.bind("<Button-3>", on_right_click)

root.mainloop()

以上就是基于Python編寫(xiě)端口進(jìn)程管理工具的詳細(xì)內(nèi)容,更多關(guān)于Python端口進(jìn)程管理工具的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python中Django文件上傳方法詳解

    python中Django文件上傳方法詳解

    在本篇文章里小編給大家整理了一篇關(guān)于python中Django文件上傳方法,有興趣的朋友們可以學(xué)習(xí)下。
    2020-08-08
  • python中ImageTk.PhotoImage()不顯示圖片卻不報(bào)錯(cuò)問(wèn)題解決

    python中ImageTk.PhotoImage()不顯示圖片卻不報(bào)錯(cuò)問(wèn)題解決

    這篇文章主要給大家介紹了關(guān)于在python中ImageTk.PhotoImage()不顯示圖片卻不報(bào)錯(cuò)問(wèn)題的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2018-12-12
  • 經(jīng)驗(yàn)豐富程序員才知道的15種高級(jí)Python小技巧(收藏)

    經(jīng)驗(yàn)豐富程序員才知道的15種高級(jí)Python小技巧(收藏)

    本文將介紹15個(gè)簡(jiǎn)潔的Python技巧,向著簡(jiǎn)潔更高效,學(xué)習(xí)易懂出發(fā),具說(shuō)只有經(jīng)驗(yàn)豐富程序員才知道的15種高級(jí)Python小技巧,喜歡的朋友快來(lái)看看吧
    2021-10-10
  • 淺析Python3 pip換源問(wèn)題

    淺析Python3 pip換源問(wèn)題

    這篇文章主要介紹了Python3 pip換源問(wèn)題,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-01-01
  • Python3標(biāo)準(zhǔn)庫(kù)glob文件名模式匹配的問(wèn)題

    Python3標(biāo)準(zhǔn)庫(kù)glob文件名模式匹配的問(wèn)題

    glob的模式規(guī)則與re模塊使用的正則表達(dá)式并不相同。實(shí)際上,glob的模式遵循標(biāo)準(zhǔn)UNIX路徑擴(kuò)展規(guī)則。只使用幾個(gè)特殊字符來(lái)實(shí)現(xiàn)兩個(gè)不同的通配符和字符區(qū)間。這篇文章主要介紹了Python3標(biāo)準(zhǔn)庫(kù)glob文件名模式匹配的知識(shí),需要的朋友可以參考下
    2020-03-03
  • python re.match函數(shù)的具體使用

    python re.match函數(shù)的具體使用

    本文主要介紹了python re.match函數(shù)的具體使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-02-02
  • python可視化 matplotlib畫(huà)圖使用colorbar工具自定義顏色

    python可視化 matplotlib畫(huà)圖使用colorbar工具自定義顏色

    這篇文章主要介紹了python可視化 matplotlib畫(huà)圖使用colorbar工具自定義顏色,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12
  • Python簡(jiǎn)單刪除列表中相同元素的方法示例

    Python簡(jiǎn)單刪除列表中相同元素的方法示例

    這篇文章主要介紹了Python簡(jiǎn)單刪除列表中相同元素的方法,結(jié)合具體實(shí)例形式分析了Python使用list、set方法針對(duì)列表元素的去重與排序操作實(shí)現(xiàn)技巧,非常簡(jiǎn)單實(shí)用,需要的朋友可以參考下
    2017-06-06
  • Python random模塊常用方法

    Python random模塊常用方法

    這篇文章主要介紹了Python random模塊常用方法,本文羅列了最常用的方法,需要的朋友可以參考下
    2014-11-11
  • 基于python代碼實(shí)現(xiàn)簡(jiǎn)易濾除數(shù)字的方法

    基于python代碼實(shí)現(xiàn)簡(jiǎn)易濾除數(shù)字的方法

    今天小編就為大家分享一篇基于python代碼實(shí)現(xiàn)簡(jiǎn)易濾除數(shù)字的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-07-07

最新評(píng)論