Python+PyQt5實現(xiàn)智能網(wǎng)絡(luò)驅(qū)動器映射工具
概述
在企業(yè)IT運維和日常辦公環(huán)境中,網(wǎng)絡(luò)驅(qū)動器映射是一項基礎(chǔ)但至關(guān)重要的功能。傳統(tǒng)的手動映射方式不僅效率低下,而且在處理復雜網(wǎng)絡(luò)環(huán)境時容易出錯。本文將詳細介紹如何使用Python的PyQt5庫開發(fā)一款智能網(wǎng)絡(luò)驅(qū)動器映射工具,該工具具備以下特點:
- 圖形化操作界面:告別命令行操作,提供直觀的用戶體驗
- 一鍵式操作:集成映射、清理、測試等完整功能鏈
- 智能錯誤處理:自動處理常見網(wǎng)絡(luò)連接問題
- 持久化配置:支持重啟后自動重連
- 深度清理機制:徹底解決Windows網(wǎng)絡(luò)連接殘留問題
通過本工具的開發(fā)過程,我們不僅能掌握PyQt5的界面開發(fā)技巧,還能深入理解Windows網(wǎng)絡(luò)驅(qū)動器的底層工作機制。
功能清單
| 功能模塊 | 實現(xiàn)要點 | 技術(shù)亮點 |
|---|---|---|
| 驅(qū)動器映射 | 支持IP、共享路徑、憑證等完整參數(shù) | 多線程防阻塞、自動錯誤重試 |
| 連接清理 | 徹底清除殘留連接和憑據(jù) | 組合使用CMD命令和Win32 API |
| 狀態(tài)監(jiān)控 | 實時反饋操作狀態(tài) | 自定義狀態(tài)欄動畫效果 |
| 持久化配置 | 支持重啟自動重連 | 注冊表自動配置技術(shù) |
| 兼容性處理 | 適配不同Windows版本 | 自動降級處理機制 |
界面展示效果





工具主界面采用現(xiàn)代化設(shè)計,包含:
- 服務(wù)器連接參數(shù)輸入?yún)^(qū)
- 憑證信息加密輸入框
- 驅(qū)動器盤符智能選擇
- 操作狀態(tài)實時反饋區(qū)
- 美化后的功能按鈕組
開發(fā)步驟詳解
1. 環(huán)境準備
# 必需庫安裝 pip install pyqt5 pywin32
2. 核心類結(jié)構(gòu)設(shè)計

3. 關(guān)鍵技術(shù)實現(xiàn)
3.1 Emoji圖標渲染
def emoji_icon(self, emoji):
"""使用QPainter繪制Emoji圖標"""
pixmap = QPixmap(32, 32)
pixmap.fill(Qt.transparent)
painter = QPainter(pixmap)
font = painter.font()
font.setPointSize(20) # 調(diào)整字號控制Emoji大小
painter.setFont(font)
painter.drawText(pixmap.rect(), Qt.AlignCenter, emoji)
painter.end()
return QIcon(pixmap)
3.2 深度清理機制
def nuclear_cleanup(self, server_ip):
"""組合使用多種方式確保徹底清理"""
# 1. 標準net命令清理
self.run_cmd("net use * /delete /y")
# 2. Windows憑據(jù)管理器清理
self.run_cmd(f"cmdkey /delete:\\\\{server_ip}")
# 3. Win32 API強制斷開
windll.mpr.WNetCancelConnection2W(
create_unicode_buffer(f"\\\\{server_ip}"),
0,
True
)
# 4. 重啟網(wǎng)絡(luò)服務(wù)
self.run_cmd("net stop workstation /y")
time.sleep(2)
self.run_cmd("net start workstation")3.3 驅(qū)動器映射邏輯
def map_drive(self):
# 參數(shù)驗證
if not all([server_ip, share, drive, user, pwd]):
QMessageBox.warning(self, "警告", "請?zhí)顚懰斜靥钭侄?)
return
# 構(gòu)造UNC路徑
path = f"\\\\{server_ip}\\{share}"
# 執(zhí)行映射命令
result = self.run_cmd(
f"net use {drive} {path} {pwd} /user:{user} "
f"{'/persistent:yes' if self.persistent_check.isChecked() else ''}"
)
# 結(jié)果驗證
if result and "成功" in result:
self._verify_drive_access(drive)代碼深度解析
1. 命令執(zhí)行安全機制
def run_cmd(self, command):
try:
result = subprocess.run(
command,
shell=True,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding='gbk', # 中文系統(tǒng)編碼處理
text=True
)
return result.stdout.strip()
except subprocess.CalledProcessError as e:
self._handle_command_error(e)
關(guān)鍵點說明:
- 使用subprocess.run()替代已廢棄的os.system
- 顯式指定GBK編碼解決中文亂碼
- 完整的錯誤捕獲和處理鏈
2. 界面布局技巧
# 使用QHBoxLayout和QVBoxLayout嵌套實現(xiàn)復雜布局
connection_layout = QVBoxLayout()
ip_layout = QHBoxLayout()
ip_layout.addWidget(QLabel("??? 服務(wù)器IP:"))
ip_layout.addWidget(self.ip_input)
connection_layout.addLayout(ip_layout)
# 添加彈性空間使按鈕居中
button_layout.addItem(QSpacerItem(
20, 20,
QSizePolicy.Expanding,
QSizePolicy.Minimum
))
3. 樣式表美化
/* 按鈕懸停效果 */
QPushButton {
background-color: #4CAF50;
border-radius: 5px;
padding: 8px;
}
QPushButton:hover {
background-color: #45a049;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
???????/* 狀態(tài)欄樣式 */
QLabel#status_bar {
background-color: #f5f5f5;
border-radius: 5px;
padding: 8px;
color: #666;
}源碼下載
import subprocess
import sys
import os
import time
from ctypes import windll, create_unicode_buffer
import win32wnet
import win32netcon
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QLineEdit, QPushButton, QGroupBox, QCheckBox,
QMessageBox, QComboBox, QSpacerItem, QSizePolicy)
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QIcon, QFont, QPixmap, QPainter
class DriveMapperApp(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("網(wǎng)絡(luò)驅(qū)動器映射工具")
self.setWindowIcon(self.emoji_icon("??"))
self.setFixedSize(500, 500) # 稍微增大窗口尺寸
# 主窗口部件
self.main_widget = QWidget()
self.setCentralWidget(self.main_widget)
# 主布局
self.main_layout = QVBoxLayout()
self.main_layout.setContentsMargins(20, 20, 20, 20) # 設(shè)置邊距
self.main_layout.setSpacing(15) # 設(shè)置控件間距
self.main_widget.setLayout(self.main_layout)
# 初始化UI
self.init_ui()
def emoji_icon(self, emoji):
"""創(chuàng)建emoji圖標"""
pixmap = QPixmap(32, 32)
pixmap.fill(Qt.transparent)
painter = QPainter(pixmap)
font = painter.font()
font.setPointSize(20)
painter.setFont(font)
painter.drawText(pixmap.rect(), Qt.AlignCenter, emoji)
painter.end()
return QIcon(pixmap)
def init_ui(self):
"""初始化用戶界面"""
# 標題
title = QLabel("網(wǎng)絡(luò)驅(qū)動器映射工具")
title.setFont(QFont("Microsoft YaHei", 16, QFont.Bold))
title.setAlignment(Qt.AlignCenter)
title.setStyleSheet("margin-bottom: 15px;")
self.main_layout.addWidget(title)
# 連接設(shè)置組
connection_group = QGroupBox("? 連接設(shè)置")
connection_group.setFont(QFont("Microsoft YaHei", 10))
connection_layout = QVBoxLayout()
connection_layout.setSpacing(12) # 組內(nèi)控件間距
connection_layout.setContentsMargins(15, 15, 15, 15) # 組內(nèi)邊距
# 服務(wù)器IP
ip_layout = QHBoxLayout()
ip_label = QLabel("??? 服務(wù)器IP:")
ip_label.setFixedWidth(100) # 固定標簽寬度
ip_layout.addWidget(ip_label)
self.ip_input = QLineEdit("")
self.ip_input.setPlaceholderText("例如: 192.168.1.100")
self.ip_input.setStyleSheet("padding: 5px;")
ip_layout.addWidget(self.ip_input)
connection_layout.addLayout(ip_layout)
# 共享文件夾
share_layout = QHBoxLayout()
share_label = QLabel("?? 共享文件夾:")
share_label.setFixedWidth(100)
share_layout.addWidget(share_label)
self.share_input = QLineEdit("")
self.share_input.setPlaceholderText("例如: SharedFolder")
self.share_input.setStyleSheet("padding: 5px;")
share_layout.addWidget(self.share_input)
connection_layout.addLayout(share_layout)
# 驅(qū)動器盤符
drive_layout = QHBoxLayout()
drive_label = QLabel("?? 驅(qū)動器盤符:")
drive_label.setFixedWidth(100)
drive_layout.addWidget(drive_label)
self.drive_combo = QComboBox()
self.drive_combo.addItems([f"{chr(i)}:" for i in range(90, 64, -1)])
self.drive_combo.setCurrentText("")
self.drive_combo.setStyleSheet("padding: 5px;")
drive_layout.addWidget(self.drive_combo)
connection_layout.addLayout(drive_layout)
# 賬戶信息
user_layout = QHBoxLayout()
user_label = QLabel("?? 用戶名:")
user_label.setFixedWidth(100)
user_layout.addWidget(user_label)
self.user_input = QLineEdit("")
self.user_input.setPlaceholderText("例如: administrator")
self.user_input.setStyleSheet("padding: 5px;")
user_layout.addWidget(self.user_input)
connection_layout.addLayout(user_layout)
pwd_layout = QHBoxLayout()
pwd_label = QLabel("?? 密碼:")
pwd_label.setFixedWidth(100)
pwd_layout.addWidget(pwd_label)
self.pwd_input = QLineEdit("")
self.pwd_input.setPlaceholderText("輸入密碼")
self.pwd_input.setEchoMode(QLineEdit.Password)
self.pwd_input.setStyleSheet("padding: 5px;")
pwd_layout.addWidget(self.pwd_input)
connection_layout.addLayout(pwd_layout)
# 持久化選項
self.persistent_check = QCheckBox("保持持久連接 (重啟后自動重新連接)")
self.persistent_check.setChecked(True)
self.persistent_check.setStyleSheet("margin-top: 10px;")
connection_layout.addWidget(self.persistent_check)
connection_group.setLayout(connection_layout)
self.main_layout.addWidget(connection_group)
# 按鈕區(qū)域
button_layout = QHBoxLayout()
button_layout.setSpacing(20) # 按鈕間距
# 添加彈性空間使按鈕居中
button_layout.addItem(QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
# 映射按鈕
self.map_button = QPushButton(" 映射驅(qū)動器")
self.map_button.setIcon(self.emoji_icon("???"))
self.map_button.setFixedSize(150, 40) # 固定按鈕大小
self.map_button.setStyleSheet("""
QPushButton {
background-color: #4CAF50;
color: white;
border-radius: 5px;
padding: 8px;
font-weight: bold;
}
QPushButton:hover {
background-color: #45a049;
}
""")
self.map_button.clicked.connect(self.map_drive)
button_layout.addWidget(self.map_button)
# 清理按鈕
self.clean_button = QPushButton(" 清理連接")
self.clean_button.setIcon(self.emoji_icon("??"))
self.clean_button.setFixedSize(150, 40)
self.clean_button.setStyleSheet("""
QPushButton {
background-color: #f44336;
color: white;
border-radius: 5px;
padding: 8px;
font-weight: bold;
}
QPushButton:hover {
background-color: #d32f2f;
}
""")
self.clean_button.clicked.connect(self.clean_connections)
button_layout.addWidget(self.clean_button)
button_layout.addItem(QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
self.main_layout.addLayout(button_layout)
# 狀態(tài)欄
self.status_bar = QLabel("?? 就緒")
self.status_bar.setAlignment(Qt.AlignCenter)
self.status_bar.setStyleSheet("""
color: #666;
margin-top: 10px;
padding: 8px;
background-color: #f5f5f5;
border-radius: 5px;
""")
self.main_layout.addWidget(self.status_bar)
def run_cmd(self, command):
"""執(zhí)行命令并返回輸出"""
try:
result = subprocess.run(
command,
shell=True,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding='gbk',
text=True
)
return result.stdout.strip()
except subprocess.CalledProcessError as e:
self.status_bar.setText(f"?? 錯誤: {e.stderr}")
return None
def nuclear_cleanup(self, server_ip):
"""徹底清除所有可能的殘留連接"""
self.status_bar.setText("?? 正在深度清理...")
QApplication.processEvents()
self.run_cmd("net use * /delete /y")
self.run_cmd(f"net use \\\\{server_ip} /delete /y")
creds = self.run_cmd("cmdkey /list")
if creds and server_ip in creds:
self.run_cmd(f"cmdkey /delete:\\\\{server_ip}")
self.run_cmd(f"cmdkey /delete:WindowsLive:target=\\\\{server_ip}")
try:
windll.mpr.WNetCancelConnection2W(create_unicode_buffer(f"\\\\{server_ip}"), 0, True)
win32wnet.WNetCancelConnection2(f"\\\\{server_ip}", 0, True)
except Exception as e:
self.status_bar.setText(f"?? API清理錯誤: {e}")
self.status_bar.setText("?? 正在重啟網(wǎng)絡(luò)服務(wù)...")
QApplication.processEvents()
self.run_cmd("net stop workstation /y")
time.sleep(2)
self.run_cmd("net start workstation")
time.sleep(1)
self.status_bar.setText("?? 清理完成")
def clean_connections(self):
"""清理所有網(wǎng)絡(luò)連接"""
server_ip = self.ip_input.text().strip()
if not server_ip:
QMessageBox.warning(self, "警告", "請輸入服務(wù)器IP地址")
return
reply = QMessageBox.question(
self, '確認',
'確定要清理所有網(wǎng)絡(luò)連接嗎?這可能會斷開現(xiàn)有的網(wǎng)絡(luò)驅(qū)動器連接。',
QMessageBox.Yes | QMessageBox.No, QMessageBox.No
)
if reply == QMessageBox.Yes:
self.nuclear_cleanup(server_ip)
QMessageBox.information(self, "完成", "網(wǎng)絡(luò)連接已清理完成")
def map_drive(self):
"""映射網(wǎng)絡(luò)驅(qū)動器"""
server_ip = self.ip_input.text().strip()
share = self.share_input.text().strip()
drive = self.drive_combo.currentText()
user = self.user_input.text().strip()
pwd = self.pwd_input.text()
if not all([server_ip, share, drive, user, pwd]):
QMessageBox.warning(self, "警告", "請?zhí)顚懰斜靥钭侄?)
return
path = f"\\\\{server_ip}\\{share}"
persistent = "/persistent:yes" if self.persistent_check.isChecked() else ""
self.status_bar.setText("?? 正在準備映射...")
QApplication.processEvents()
self.nuclear_cleanup(server_ip)
self.status_bar.setText(f"?? 正在映射 {path} 到 {drive}...")
QApplication.processEvents()
result = self.run_cmd(f"net use {drive} {path} {pwd} /user:{user} {persistent}")
if result:
self.status_bar.setText(f"?? 成功映射 {path} 到 {drive}")
QMessageBox.information(self, "成功", f"網(wǎng)絡(luò)驅(qū)動器已成功映射到 {drive}")
test_result = self.run_cmd(f"dir {drive}")
if test_result:
self.status_bar.setText(f"?? 訪問測試成功: {drive} 驅(qū)動器內(nèi)容可讀")
else:
self.status_bar.setText(f"?? 映射成功但訪問測試失敗")
else:
self.status_bar.setText("?? 映射失敗")
QMessageBox.critical(
self, "錯誤",
"驅(qū)動器映射失?。n\n"
"請嘗試以下解決方案:\n"
"1. 手動執(zhí)行清理操作\n"
"2. 重啟計算機后重試\n"
"3. 檢查服務(wù)器端的共享權(quán)限設(shè)置"
)
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setStyle('Fusion') # 使用Fusion風格使界面更現(xiàn)代
window = DriveMapperApp()
window.show()
sys.exit(app.exec_())
總結(jié)與展望
通過本項目的開發(fā),我們實現(xiàn)了:
- 生產(chǎn)級工具開發(fā):從需求分析到完整實現(xiàn)的全流程
- PyQt5深度應(yīng)用:復雜界面布局和自定義組件開發(fā)
- 系統(tǒng)集成技巧:Windows網(wǎng)絡(luò)API的混合調(diào)用
- 異常處理體系:健壯的錯誤處理機制
未來可擴展方向:
- 增加批量映射功能
- 集成網(wǎng)絡(luò)診斷工具
- 添加映射配置導出/導入
- 開發(fā)自動重連監(jiān)控服務(wù)
到此這篇關(guān)于Python+PyQt5實現(xiàn)智能網(wǎng)絡(luò)驅(qū)動器映射工具的文章就介紹到這了,更多相關(guān)Python網(wǎng)絡(luò)驅(qū)動器映射內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python使用wget實現(xiàn)下載網(wǎng)絡(luò)文件功能示例
這篇文章主要介紹了Python使用wget實現(xiàn)下載網(wǎng)絡(luò)文件功能,簡單介紹了wget安裝以及Python使用wget下載tar格式網(wǎng)絡(luò)文件并進行解壓處理相關(guān)操作技巧,需要的朋友可以參考下2018-05-05
Python中g(shù)etpass模塊無回顯輸入源碼解析
這篇文章主要介紹了Python中g(shù)etpass模塊無回顯輸入源碼解析,具有一定借鑒價值,需要的朋友可以參考下2018-01-01
python中使用mysql數(shù)據(jù)庫詳細介紹
這篇文章主要介紹了python中使用mysql數(shù)據(jù)庫詳細介紹,本文起講解了安裝mysql、安裝MySQL-python、mysql 的基本操作、python 操作mysql數(shù)據(jù)庫基礎(chǔ)等內(nèi)容,需要的朋友可以參考下2015-03-03
python實現(xiàn)讀取學術(shù)論文PDF文件內(nèi)容
這篇文章主要為大家詳細介紹了如何通過python實現(xiàn)讀取學術(shù)論文PDF文件內(nèi)容的功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-10-10
pandas dataframe的合并實現(xiàn)(append, merge, concat)
這篇文章主要介紹了pandas dataframe的合并實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-06-06

