开源解析:Python 打造专业级 USB 安全弹出工具(附完整源码)

在许多操作系统中,拔出 USB 存储设备时,经常会遇到 “设备正被使用” 的错误提示。为了保证数据的安全性,避免在使用过程中突然拔出 USB 设备而导致数据丢失或损坏,开发一个自动安全弹出的工具就显得尤为重要。通过 Python,结合操作系统的底层接口,可以很容易地实现一个专业级的 USB 安全弹出工具。

1. USB 安全弹出的概述

USB 安全弹出工具主要有两个目标:

  • 确保文件系统已被卸载:即所有文件操作完成,确保没有进程或线程正在访问 USB 存储。
  • 执行安全的设备卸载:确保系统不再使用 USB 设备后,可以安全地从系统中弹出。

为了达到这个目标,我们需要调用操作系统的底层API,或者通过命令行工具来操作。

2. 如何使用 Python 实现 USB 安全弹出

我们可以使用 Python 的 ossubprocess 和 ctypes 模块来与操作系统进行交互。具体步骤如下:

  1. 获取系统中的 USB 设备
  2. 检查设备是否正在使用
  3. 调用系统命令安全卸载设备

3. 安全弹出 USB 的跨平台实现

我们将分别实现 Windows 和 Linux 下的 USB 安全弹出功能。对于 Windows,我们可以通过 os 或 subprocess模块执行 diskpart 和 devcon 命令。而在 Linux 上,我们可以通过调用 umount 和 eject 命令来卸载 USB。

4. 安装依赖

Python 标准库提供了许多与文件系统和硬件交互的模块,但在一些操作系统上,我们需要一些外部工具来处理 USB 设备的安全弹出:

  • Windows:需要 devcon 工具来卸载设备。
  • Linux/MacOS:需要系统自带的命令行工具,如 umount 和 eject

5. Windows 系统的 USB 安全弹出工具

5.1 使用 devcon 命令

devcon 是 Windows 提供的命令行工具,用于操作设备驱动程序。我们可以通过它来禁用或卸载 USB 设备。

import os
import subprocess

def eject_usb_windows(drive_letter):
    """
    安全弹出 USB 存储设备(Windows)
    :param drive_letter: USB 驱动器的盘符(例如 "E:")
    """
    try:
        # 使用 devcon 工具卸载 USB 设备
        command = f"devcon remove \"{drive_letter}\""
        subprocess.run(command, check=True, shell=True)
        print(f"USB 设备 {drive_letter} 已成功卸载")
    except subprocess.CalledProcessError as e:
        print(f"卸载失败: {e}")

5.2 获取 USB 设备信息

你可以使用 subprocess 模块获取 Windows 中连接的所有磁盘信息,然后根据磁盘信息确定 USB 设备的盘符,来实现对设备的自动识别和卸载。

def get_usb_drives_windows():
    """
    获取当前系统中所有 USB 存储设备的盘符(Windows)
    """
    try:
        # 使用 diskpart 获取磁盘信息
        command = 'wmic logicaldisk where "drivetype=2" get deviceid, volumename, description'
        result = subprocess.run(command, check=True, shell=True, stdout=subprocess.PIPE)
        output = result.stdout.decode().strip()
        drives = []
        for line in output.splitlines():
            if line.strip():
                drives.append(line.split()[0])  # 提取盘符
        return drives
    except subprocess.CalledProcessError as e:
        print(f"获取 USB 设备失败: {e}")
        return []

6. Linux 系统的 USB 安全弹出工具

6.1 使用 umount 和 eject 命令

在 Linux 中,我们可以使用 umount 命令卸载文件系统,然后使用 eject 命令将 USB 设备弹出。

import os
import subprocess

def eject_usb_linux(mount_point):
    """
    安全弹出 USB 存储设备(Linux)
    :param mount_point: USB 设备的挂载点(例如 "/mnt/usb")
    """
    try:
        # 卸载设备
        subprocess.run(["umount", mount_point], check=True)
        # 弹出设备
        subprocess.run(["eject", mount_point], check=True)
        print(f"USB 设备 {mount_point} 已成功卸载并弹出")
    except subprocess.CalledProcessError as e:
        print(f"卸载失败: {e}")

6.2 获取 USB 设备信息

在 Linux 中,我们可以使用 lsblk 或 lsusb 命令来列出连接的 USB 设备,并获取其挂载点。

def get_usb_drives_linux():
    """
    获取当前系统中所有 USB 存储设备的挂载点(Linux)
    """
    try:
        # 使用 lsblk 获取 USB 设备的挂载点
        command = 'lsblk -o NAME,MOUNTPOINT,TYPE | grep "part"'
        result = subprocess.run(command, check=True, shell=True, stdout=subprocess.PIPE)
        output = result.stdout.decode().strip()
        drives = []
        for line in output.splitlines():
            parts = line.split()
            if len(parts) > 1 and parts[1] != "null":
                drives.append(parts[1])  # 提取挂载点
        return drives
    except subprocess.CalledProcessError as e:
        print(f"获取 USB 设备失败: {e}")
        return []

7. 完整源码:USB 安全弹出工具

import subprocess
import os
import platform

def eject_usb(drive_identifier):
    """
    根据操作系统选择合适的命令卸载 USB 设备
    :param drive_identifier: 驱动器盘符(Windows)或挂载点(Linux)
    """
    system_platform = platform.system()
    
    if system_platform == "Windows":
        eject_usb_windows(drive_identifier)
    elif system_platform == "Linux":
        eject_usb_linux(drive_identifier)
    else:
        print("不支持的操作系统")

def eject_usb_windows(drive_letter):
    """
    Windows 下弹出 USB 存储设备
    :param drive_letter: USB 驱动器的盘符(例如 "E:")
    """
    try:
        # 使用 devcon 工具卸载 USB 设备
        command = f"devcon remove \"{drive_letter}\""
        subprocess.run(command, check=True, shell=True)
        print(f"USB 设备 {drive_letter} 已成功卸载")
    except subprocess.CalledProcessError as e:
        print(f"卸载失败: {e}")

def eject_usb_linux(mount_point):
    """
    Linux 下弹出 USB 存储设备
    :param mount_point: USB 设备的挂载点(例如 "/mnt/usb")
    """
    try:
        subprocess.run(["umount", mount_point], check=True)
        subprocess.run(["eject", mount_point], check=True)
        print(f"USB 设备 {mount_point} 已成功卸载并弹出")
    except subprocess.CalledProcessError as e:
        print(f"卸载失败: {e}")

if __name__ == "__main__":
    if platform.system() == "Windows":
        drive = input("请输入 USB 盘符(例如 E:):")
        eject_usb(drive)
    elif platform.system() == "Linux":
        mount_point = input("请输入 USB 挂载点(例如 /mnt/usb):")
        eject_usb(mount_point)

8. 总结

通过 Python 和操作系统的命令行工具,我们可以轻松实现一个专业级的 USB 安全弹出工具。在 Windows 中,我们可以使用 devcon 命令来卸载 USB 设备,而在 Linux 系统中,我们可以通过 umount 和 eject 命令来实现相同的功能。

这个工具不仅可以确保在拔出设备之前文件系统已被卸载,还可以确保设备的安全弹出,防止文件损坏或数据丢失。