You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python将Windows UNC路径转换为映射驱动器盘符路径?

将UNC路径转换为Windows映射盘符路径

要把UNC路径转换成对应的盘符路径,核心是找到该UNC共享已映射的驱动器盘符,下面提供几种Python实现方案:

方案1:用ctypes调用Windows API(无需额外依赖)

Windows系统提供了WNetGetConnection API,可以查询共享路径对应的映射盘符。先从UNC路径中提取根共享部分,再调用API获取盘符:

import ctypes
from ctypes import wintypes
import pathlib

def unc_to_drive_path(unc_path):
    path = pathlib.Path(unc_path)
    # 提取UNC根共享(比如\\my.subnet\someplace)
    unc_root = path.drive
    if not unc_root.startswith('\\\\'):
        raise ValueError("输入不是有效的UNC路径")
    
    # 调用WNetGetConnection API
    WNetGetConnection = ctypes.windll.mpr.WNetGetConnectionW
    WNetGetConnection.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.LPDWORD]
    WNetGetConnection.restype = wintypes.DWORD
    
    buffer_size = wintypes.DWORD(256)
    drive_buffer = ctypes.create_unicode_buffer(buffer_size.value)
    
    result = WNetGetConnection(unc_root[2:], drive_buffer, ctypes.byref(buffer_size))
    if result != 0:
        raise OSError(f"无法找到映射的盘符,错误码: {result}")
    
    # 拼接盘符和剩余路径
    drive_letter = drive_buffer.value.rstrip('\\')
    return str(pathlib.Path(drive_letter) / path.relative_to(unc_root))

# 示例使用
unc_path = r"\\my.subnet\someplace\Some\Path\file.txt"
try:
    drive_path = unc_to_drive_path(unc_path)
    print(drive_path)  # 输出类似 M:\Some\Path\file.txt
except Exception as e:
    print(f"转换失败: {e}")

方案2:使用pywin32库(更简洁)

如果可以安装第三方库,pywin32的win32wnet模块封装了相关API,代码更简洁:

import pathlib
import win32wnet

def unc_to_drive_path(unc_path):
    path = pathlib.Path(unc_path)
    unc_root = path.drive
    if not unc_root.startswith('\\\\'):
        raise ValueError("输入不是有效的UNC路径")
    
    # 获取映射盘符
    drive_letter = win32wnet.WNetGetConnection(unc_root[2:])
    # 拼接路径
    return str(pathlib.Path(drive_letter) / path.relative_to(unc_root))

# 示例使用
unc_path = r"\\my.subnet\someplace\Some\Path\file.txt"
try:
    print(unc_to_drive_path(unc_path))
except win32wnet.error as e:
    print(f"转换失败: {e}")

方案3:解析net use命令输出(无需额外依赖)

通过执行net use命令,解析输出找到共享对应的盘符:

import subprocess
import pathlib
import re

def unc_to_drive_path(unc_path):
    path = pathlib.Path(unc_path)
    unc_root = path.drive
    if not unc_root.startswith('\\\\'):
        raise ValueError("输入不是有效的UNC路径")
    
    # 执行net use命令并获取输出
    result = subprocess.run(['net', 'use'], capture_output=True, text=True, encoding='gbk')
    if result.returncode != 0:
        raise OSError(f"执行net use失败: {result.stderr}")
    
    # 匹配共享路径和盘符的正则
    pattern = re.compile(r'([A-Z]):\s+\\\\(.+?)\\(.+?)')
    for line in result.stdout.splitlines():
        match = pattern.search(line)
        if match:
            drive = match.group(1)
            share = f"\\\\{match.group(2)}\\{match.group(3)}"
            if share == unc_root:
                # 拼接路径
                return str(pathlib.Path(f"{drive}:") / path.relative_to(unc_root))
    
    raise ValueError(f"未找到UNC共享 {unc_root} 对应的映射盘符")

# 示例使用
unc_path = r"\\my.subnet\someplace\Some\Path\file.txt"
try:
    print(unc_to_drive_path(unc_path))
except Exception as e:
    print(f"转换失败: {e}")

注意:以上方案都要求UNC共享已经被映射为本地盘符,如果没有映射,转换会失败,此时可考虑添加自动映射逻辑(需对应权限)。

内容的提问来源于stack exchange,提问作者auslander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 03:20:14