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

Python+PyQt5實現智能網絡驅動器映射工具

 更新時間:2025年06月13日 08:51:44   作者:創(chuàng)客白澤  
在企業(yè)IT運維和日常辦公環(huán)境中,網絡驅動器映射是一項基礎但至關重要的功能,本文將詳細介紹如何使用Python的PyQt5庫開發(fā)一款智能網絡驅動器映射工具,有需要的可以了解下

概述

在企業(yè)IT運維和日常辦公環(huán)境中,網絡驅動器映射是一項基礎但至關重要的功能。傳統的手動映射方式不僅效率低下,而且在處理復雜網絡環(huán)境時容易出錯。本文將詳細介紹如何使用Python的PyQt5庫開發(fā)一款智能網絡驅動器映射工具,該工具具備以下特點:

  • 圖形化操作界面:告別命令行操作,提供直觀的用戶體驗
  • 一鍵式操作:集成映射、清理、測試等完整功能鏈
  • 智能錯誤處理:自動處理常見網絡連接問題
  • 持久化配置:支持重啟后自動重連
  • 深度清理機制:徹底解決Windows網絡連接殘留問題

通過本工具的開發(fā)過程,我們不僅能掌握PyQt5的界面開發(fā)技巧,還能深入理解Windows網絡驅動器的底層工作機制。

功能清單

功能模塊實現要點技術亮點
驅動器映射支持IP、共享路徑、憑證等完整參數多線程防阻塞、自動錯誤重試
連接清理徹底清除殘留連接和憑據組合使用CMD命令和Win32 API
狀態(tài)監(jiān)控實時反饋操作狀態(tài)自定義狀態(tài)欄動畫效果
持久化配置支持重啟自動重連注冊表自動配置技術
兼容性處理適配不同Windows版本自動降級處理機制

界面展示效果

工具主界面采用現代化設計,包含:

  • 服務器連接參數輸入區(qū)
  • 憑證信息加密輸入框
  • 驅動器盤符智能選擇
  • 操作狀態(tài)實時反饋區(qū)
  • 美化后的功能按鈕組

開發(fā)步驟詳解

1. 環(huán)境準備

# 必需庫安裝
pip install pyqt5 pywin32

2. 核心類結構設計

3. 關鍵技術實現

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)  # 調整字號控制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憑據管理器清理
    self.run_cmd(f"cmdkey /delete:\\\\{server_ip}")
    
    # 3. Win32 API強制斷開
    windll.mpr.WNetCancelConnection2W(
        create_unicode_buffer(f"\\\\{server_ip}"), 
        0, 
        True
    )
    
    # 4. 重啟網絡服務
    self.run_cmd("net stop workstation /y")
    time.sleep(2)
    self.run_cmd("net start workstation")

3.3 驅動器映射邏輯

def map_drive(self):
    # 參數驗證
    if not all([server_ip, share, drive, user, pwd]):
        QMessageBox.warning(self, "警告", "請?zhí)顚懰斜靥钭侄?)
        return
    
    # 構造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 ''}"
    )
    
    # 結果驗證
    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',  # 中文系統編碼處理
            text=True
        )
        return result.stdout.strip()
    except subprocess.CalledProcessError as e:
        self._handle_command_error(e)

關鍵點說明:

  • 使用subprocess.run()替代已廢棄的os.system
  • 顯式指定GBK編碼解決中文亂碼
  • 完整的錯誤捕獲和處理鏈

2. 界面布局技巧

# 使用QHBoxLayout和QVBoxLayout嵌套實現復雜布局
connection_layout = QVBoxLayout()
ip_layout = QHBoxLayout()
ip_layout.addWidget(QLabel("??? 服務器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("網絡驅動器映射工具")
        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)  # 設置邊距
        self.main_layout.setSpacing(15)  # 設置控件間距
        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("網絡驅動器映射工具")
        title.setFont(QFont("Microsoft YaHei", 16, QFont.Bold))
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("margin-bottom: 15px;")
        self.main_layout.addWidget(title)
        
        # 連接設置組
        connection_group = QGroupBox("? 連接設置")
        connection_group.setFont(QFont("Microsoft YaHei", 10))
        connection_layout = QVBoxLayout()
        connection_layout.setSpacing(12)  # 組內控件間距
        connection_layout.setContentsMargins(15, 15, 15, 15)  # 組內邊距
        
        # 服務器IP
        ip_layout = QHBoxLayout()
        ip_label = QLabel("??? 服務器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)
        
        # 驅動器盤符
        drive_layout = QHBoxLayout()
        drive_label = QLabel("?? 驅動器盤符:")
        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(" 映射驅動器")
        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("?? 正在重啟網絡服務...")
        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):
        """清理所有網絡連接"""
        server_ip = self.ip_input.text().strip()
        if not server_ip:
            QMessageBox.warning(self, "警告", "請輸入服務器IP地址")
            return
            
        reply = QMessageBox.question(
            self, '確認',
            '確定要清理所有網絡連接嗎?這可能會斷開現有的網絡驅動器連接。',
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            self.nuclear_cleanup(server_ip)
            QMessageBox.information(self, "完成", "網絡連接已清理完成")
    
    def map_drive(self):
        """映射網絡驅動器"""
        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"網絡驅動器已成功映射到 {drive}")
            
            test_result = self.run_cmd(f"dir {drive}")
            if test_result:
                self.status_bar.setText(f"?? 訪問測試成功: {drive} 驅動器內容可讀")
            else:
                self.status_bar.setText(f"?? 映射成功但訪問測試失敗")
        else:
            self.status_bar.setText("?? 映射失敗")
            QMessageBox.critical(
                self, "錯誤", 
                "驅動器映射失??!\n\n"
                "請嘗試以下解決方案:\n"
                "1. 手動執(zhí)行清理操作\n"
                "2. 重啟計算機后重試\n"
                "3. 檢查服務器端的共享權限設置"
            )

if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setStyle('Fusion')  # 使用Fusion風格使界面更現代
    window = DriveMapperApp()
    window.show()
    sys.exit(app.exec_())

總結與展望

通過本項目的開發(fā),我們實現了:

  • 生產級工具開發(fā):從需求分析到完整實現的全流程
  • PyQt5深度應用:復雜界面布局和自定義組件開發(fā)
  • 系統集成技巧:Windows網絡API的混合調用
  • 異常處理體系:健壯的錯誤處理機制

未來可擴展方向:

  • 增加批量映射功能
  • 集成網絡診斷工具
  • 添加映射配置導出/導入
  • 開發(fā)自動重連監(jiān)控服務

到此這篇關于Python+PyQt5實現智能網絡驅動器映射工具的文章就介紹到這了,更多相關Python網絡驅動器映射內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • pampy超強的模式匹配工具的實現

    pampy超強的模式匹配工具的實現

    在自然語言處理界,模式匹配可以說是最常用的技術。甚至可以說,將NLP技術作為真實生產力的項目都少不了模式匹配。本文就介紹了pampy超強的模式匹配工具的實現,感興趣的可以了解一下
    2021-07-07
  • Keras在訓練期間可視化訓練誤差和測試誤差實例

    Keras在訓練期間可視化訓練誤差和測試誤差實例

    這篇文章主要介紹了Keras在訓練期間可視化訓練誤差和測試誤差實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • Python3.10的一些新特性原理分析

    Python3.10的一些新特性原理分析

    由于采用了新的發(fā)行計劃:PEP 602 -- Annual Release Cycle for Python,我們可以看到更短的開發(fā)窗口,我們有望在 2021 年 10 月使用今天分享的這些新特性
    2021-09-09
  • python腳本作為Windows服務啟動代碼詳解

    python腳本作為Windows服務啟動代碼詳解

    本篇文章給大家分享了用python腳本寫出作為Windows服務啟動功能,對此有需求的朋友跟著小編一起學習下。
    2018-02-02
  • Python切圖九宮格的實現方法

    Python切圖九宮格的實現方法

    這篇文章主要介紹了Python切圖九宮格的實現方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-10-10
  • Numpy?數據處理?ndarray使用詳解

    Numpy?數據處理?ndarray使用詳解

    這篇文章主要為大家介紹了Numpy?數據處理?ndarray使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-08-08
  • Python numpy.array()生成相同元素數組的示例

    Python numpy.array()生成相同元素數組的示例

    今天小編就為大家分享一篇Python numpy.array()生成相同元素數組的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-11-11
  • 使用grappelli為django admin后臺添加模板

    使用grappelli為django admin后臺添加模板

    本文介紹了一款非常流行的Django模板系統--grappelli,以及如何給Django的admin后臺添加模板,非常的實用,這里推薦給大家。
    2014-11-11
  • Python使用PyMongo4.x操作MongoDB的教程分享

    Python使用PyMongo4.x操作MongoDB的教程分享

    PyMongo是一個Python編程語言中用于連接和操作MongoDB數據庫的庫,它提供了豐富的功能和API,使開發(fā)者能夠在Python中輕松地進行MongoDB的數據交互和管理,本文給大家總結了Python如何使用PyMongo4.x操作MongoDB,需要的朋友可以參考下
    2023-09-09
  • python字符串替換re.sub()方法解析

    python字符串替換re.sub()方法解析

    這篇文章主要介紹了python字符串替換re.sub()方法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-09-09

最新評論