基于Python編寫端口進程管理工具
1. 簡介
這是我用python寫的一個用于端口管理和進程管理的GUI工具,它可以顯示當前系統(tǒng)上所有開放的端口信息,并且允許用戶對選中的進程進行操作(如結(jié)束進程、定位進程文件夾路徑、復制相關(guān)信息到剪貼板等)。
具體的功能包括:
- 獲取系統(tǒng)的開放端口信息,包括端口號、進程名稱、協(xié)議類型(TCP/UDP)和進程路徑。
- 支持端口號、進程名稱、PID的搜索。
- 提供右鍵菜單,可以執(zhí)行結(jié)束進程、定位進程路徑、復制信息等操作。
- 支持表格視圖的滾動,可以查看大量端口數(shù)據(jù)。
- 支持數(shù)據(jù)刷新,更新顯示系統(tǒng)當前開放的端口和進程。
關(guān)鍵功能解析
- 獲取本機開放的端口信息:
- 使用 psutil.net_connections(kind=‘inet’) 獲取當前的網(wǎng)絡連接信息,篩選出狀態(tài)為 LISTEN的連接(即開放的端口)。
- 獲取與端口相關(guān)的進程信息,包括 PID、進程名稱、進程路徑等。
搜索功能:
- 可以通過端口號、進程名稱或 PID 搜索對應的端口和進程。
- 用戶可以輸入查詢的內(nèi)容,選擇查詢的類型,點擊查詢按鈕后,展示匹配的端口信息。
右鍵菜單:
- 右鍵點擊某一行端口數(shù)據(jù)時,會彈出一個菜單,菜單中包含結(jié)束進程、定位進程文件夾路徑、復制信息等選項。
- 結(jié)束進程:通過 psutil.Process(pid).terminate() 來結(jié)束選中的進程。
- 定位進程文件夾路徑:使用 os.startfile() 打開進程所在的文件夾。
- 復制到剪貼板:使用 pyperclip.copy() 將選中的信息復制到系統(tǒng)剪貼板。
UI界面:
使用 ttk.Treeview 控件顯示端口信息表格,支持垂直和水平滾動條。
創(chuàng)建了輸入框和下拉菜單,供用戶選擇查詢類型并輸入查詢內(nèi)容。
界面功能
端口表格顯示:
顯示端口的詳細信息,包括 PID、協(xié)議類型(TCP/UDP)、端口號、進程名稱和路徑。
支持垂直和水平滾動條,方便查看長列表。
查詢功能:
支持通過端口號、進程名稱、PID查詢端口信息。
提供搜索框和下拉選擇框,方便用戶選擇查詢類型。
右鍵菜單操作:
提供“結(jié)束進程”、“定位進程文件夾路徑”、“復制信息”等選項。 刷新功能:
點擊刷新按鈕可以重新加載端口信息,確保數(shù)據(jù)是最新的。
2. 運行效果


3. 相關(guān)源碼
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協(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ù)端口號查詢對應進程的信息
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ù)進程名稱查詢對應的端口信息
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查詢對應的端口信息
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']))
# 根據(jù)選擇的搜索類型執(zhí)行相應的搜索
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。")
# 結(jié)束進程
def kill_process(pid):
try:
process = psutil.Process(pid)
process.terminate() # 發(fā)送 terminate 信號
process.wait() # 等待進程結(jié)束
messagebox.showinfo("結(jié)束進程", f"進程 (PID: {pid}) 已被成功結(jié)束。")
except (psutil.NoSuchProcess, psutil.AccessDenied):
messagebox.showerror("錯誤", "無法結(jié)束該進程,可能沒有權(quá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) # 打開文件夾
else:
messagebox.showerror("錯誤", "無法找到進程文件路徑。")
# 復制到剪貼板的功能
def copy_to_clipboard(text):
pyperclip.copy(text) # 使用 pyperclip 庫復制文本
messagebox.showinfo("復制成功", "內(nèi)容已復制到剪貼板")
# 添加右鍵菜單
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] # 獲取進程名稱
exe_path = treeview.item(selected_item)['values'][4] # 獲取路徑
menu = tk.Menu(root, tearoff=0)
menu.add_command(label="結(jié)束進程", 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="復制相關(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("端口進程管理工具") # 更新窗口標題
root.geometry("968x699")
# 創(chuàng)建并配置表格
columns = ("PID", "協(xié)議", "端口", "進程名稱", "相關(guān)路徑") # 更新列順序
treeview = ttk.Treeview(root, columns=columns, show='headings', height=25)
treeview.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# 設置表頭并使內(nèi)容居中顯示
for col in columns:
treeview.heading(col, text=col)
if col in ["PID", "協(xié)議", "端口"]: # 設置PID、協(xié)議、端口列的寬度為固定10
treeview.column(col, width=10, anchor='center')
else: # 其他列自動擴展
treeview.column(col, anchor='center')
# 創(chuà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=["端口號", "進程名稱", "PID"], width=15)
combobox_search_type.pack(side=tk.LEFT, padx=5)
combobox_search_type.set("端口號") # 設置默認選項
# 輸入框 - 根據(jù)選擇的搜索類型輸入相應內(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)
# 查詢按鈕 - 設置不同尺寸
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編寫端口進程管理工具的詳細內(nèi)容,更多關(guān)于Python端口進程管理工具的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python中ImageTk.PhotoImage()不顯示圖片卻不報錯問題解決
這篇文章主要給大家介紹了關(guān)于在python中ImageTk.PhotoImage()不顯示圖片卻不報錯問題的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-12-12
經(jīng)驗豐富程序員才知道的15種高級Python小技巧(收藏)
本文將介紹15個簡潔的Python技巧,向著簡潔更高效,學習易懂出發(fā),具說只有經(jīng)驗豐富程序員才知道的15種高級Python小技巧,喜歡的朋友快來看看吧2021-10-10
python可視化 matplotlib畫圖使用colorbar工具自定義顏色
這篇文章主要介紹了python可視化 matplotlib畫圖使用colorbar工具自定義顏色,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12
基于python代碼實現(xiàn)簡易濾除數(shù)字的方法
今天小編就為大家分享一篇基于python代碼實現(xiàn)簡易濾除數(shù)字的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07

