基于Python編寫端口進(jìn)程管理工具
1. 簡介
這是我用python寫的一個用于端口管理和進(jìn)程管理的GUI工具,它可以顯示當(dāng)前系統(tǒng)上所有開放的端口信息,并且允許用戶對選中的進(jìn)程進(jìn)行操作(如結(jié)束進(jìn)程、定位進(jìn)程文件夾路徑、復(fù)制相關(guān)信息到剪貼板等)。
具體的功能包括:
- 獲取系統(tǒng)的開放端口信息,包括端口號、進(jìn)程名稱、協(xié)議類型(TCP/UDP)和進(jìn)程路徑。
- 支持端口號、進(jìn)程名稱、PID的搜索。
- 提供右鍵菜單,可以執(zhí)行結(jié)束進(jìn)程、定位進(jìn)程路徑、復(fù)制信息等操作。
- 支持表格視圖的滾動,可以查看大量端口數(shù)據(jù)。
- 支持?jǐn)?shù)據(jù)刷新,更新顯示系統(tǒng)當(dāng)前開放的端口和進(jìn)程。
關(guān)鍵功能解析
- 獲取本機(jī)開放的端口信息:
- 使用 psutil.net_connections(kind=‘inet’) 獲取當(dāng)前的網(wǎng)絡(luò)連接信息,篩選出狀態(tài)為 LISTEN的連接(即開放的端口)。
- 獲取與端口相關(guān)的進(jìn)程信息,包括 PID、進(jìn)程名稱、進(jìn)程路徑等。
搜索功能:
- 可以通過端口號、進(jìn)程名稱或 PID 搜索對應(yīng)的端口和進(jìn)程。
- 用戶可以輸入查詢的內(nèi)容,選擇查詢的類型,點(diǎn)擊查詢按鈕后,展示匹配的端口信息。
右鍵菜單:
- 右鍵點(diǎn)擊某一行端口數(shù)據(jù)時,會彈出一個菜單,菜單中包含結(jié)束進(jìn)程、定位進(jìn)程文件夾路徑、復(fù)制信息等選項(xiàng)。
- 結(jié)束進(jìn)程:通過 psutil.Process(pid).terminate() 來結(jié)束選中的進(jìn)程。
- 定位進(jìn)程文件夾路徑:使用 os.startfile() 打開進(jìn)程所在的文件夾。
- 復(fù)制到剪貼板:使用 pyperclip.copy() 將選中的信息復(fù)制到系統(tǒng)剪貼板。
UI界面:
使用 ttk.Treeview 控件顯示端口信息表格,支持垂直和水平滾動條。
創(chuàng)建了輸入框和下拉菜單,供用戶選擇查詢類型并輸入查詢內(nèi)容。
界面功能
端口表格顯示:
顯示端口的詳細(xì)信息,包括 PID、協(xié)議類型(TCP/UDP)、端口號、進(jìn)程名稱和路徑。
支持垂直和水平滾動條,方便查看長列表。
查詢功能:
支持通過端口號、進(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ī)所有開放的端口及對應(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ù)端口號查詢對應(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)程名稱查詢對應(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查詢對應(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("沒有找到端口", "沒有開放的端口或無法獲取端口信息。")
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 == "端口號":
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} 對應(yīng)的進(jìn)程。")
except ValueError:
messagebox.showerror("輸入錯誤", "請輸入有效的端口號。")
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} 對應(yīng)的進(jìn)程。")
except ValueError:
messagebox.showerror("輸入錯誤", "請輸入有效的PID。")
# 結(jié)束進(jìn)程
def kill_process(pid):
try:
process = psutil.Process(pid)
process.terminate() # 發(fā)送 terminate 信號
process.wait() # 等待進(jìn)程結(jié)束
messagebox.showinfo("結(jié)束進(jìn)程", f"進(jìn)程 (PID: {pid}) 已被成功結(jié)束。")
except (psutil.NoSuchProcess, psutil.AccessDenied):
messagebox.showerror("錯誤", "無法結(jié)束該進(jìn)程,可能沒有權(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) # 打開文件夾
else:
messagebox.showerror("錯誤", "無法找到進(jìn)程文件路徑。")
# 復(fù)制到剪貼板的功能
def copy_to_clipboard(text):
pyperclip.copy(text) # 使用 pyperclip 庫復(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ù)制端口號", 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: # 其他列自動擴(kuò)展
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=["端口號", "進(jìn)程名稱", "PID"], width=15)
combobox_search_type.pack(side=tk.LEFT, padx=5)
combobox_search_type.set("端口號") # 設(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)
# 初始化時更新端口信息
update_port_list()
# 綁定右鍵菜單
treeview.bind("<Button-3>", on_right_click)
root.mainloop()
以上就是基于Python編寫端口進(jìn)程管理工具的詳細(xì)內(nèi)容,更多關(guān)于Python端口進(jìn)程管理工具的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python?matplotlib中更換畫布背景顏色的3種方法
這篇文章主要給大家介紹了關(guān)于Python?matplotlib中更換畫布背景顏色的3種方法,在Matplotlib中,我們可以使用set_facecolor()方法來設(shè)置背景顏色,文中通過圖文以及代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-11-11
Python使用Matplotlib將爬取的CSV數(shù)據(jù)變成直觀圖表
當(dāng)你在電商網(wǎng)站爬取了10萬條商品價格數(shù)據(jù),或是從氣象站抓取了3年的溫度記錄,面對密密麻麻的CSV表格時,是否感到無從下手,本文將帶你完成一個完整的數(shù)據(jù)可視化實(shí)戰(zhàn):從爬取某招聘網(wǎng)站的職位信息,到用Matplotlib生成專業(yè)圖表,需要的朋友可以參考下2025-10-10
NumPy索引介紹之?dāng)?shù)組的索引和切片用法
NumPy的數(shù)組對象可以使用索引進(jìn)行訪問,支持基本切片、高級索引和字段訪問,基本切片拓展到多維,但返回視圖而非副本,高級索引通過整數(shù)和布爾索引實(shí)現(xiàn),使用對象是布爾類型時也會進(jìn)行高級索引,字段索引適用于結(jié)構(gòu)化數(shù)組2026-05-05
Python3.5面向?qū)ο缶幊虉D文與實(shí)例詳解
這篇文章主要介紹了Python3.5面向?qū)ο缶幊?結(jié)合圖文與實(shí)例形式詳細(xì)分析了Python面向?qū)ο缶幊滔嚓P(guān)的概念、類定義、實(shí)例化、實(shí)例變量、類變量、析構(gòu)函數(shù)等相關(guān)原理及使用技巧,需要的朋友可以參考下2019-04-04
Python實(shí)現(xiàn)List列表去重的五種方案
本文詳細(xì)介紹了Python中列表去重的多種方法,包括list(set(lst))、dict.fromkeys(lst)、列表推導(dǎo)式、pandas.Series.drop_duplicates()和sorted(list(groupby(lst)))等,并分析了它們的底層原理和效率差異,需要的朋友可以參考下2025-12-12
Python成功解決讀文件出現(xiàn):IOError:?[Errno?0]?Error的錯誤
在Python編程中,處理文件是常見的任務(wù)之一,但偶爾也會遇到各種錯誤,包括IOError,盡管Python?3.x中IOError已被OSError和FileNotFoundError等更具體的異常所取代,由于[Errno?0]不直接指向具體的錯誤類型,我們將討論一系列可能導(dǎo)致IOError的常見情況,需要的朋友可以參考下2024-07-07

