从python中的网络驱动器号获取完整的计算机名称 [英] Get full computer name from a network drive letter in python

查看:423
本文介绍了从python中的网络驱动器号获取完整的计算机名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python用大量已存储文件的文件路径填充表.但是,该路径需要具有完整的网络驱动器计算机名称,而不仅仅是驱动器号,即

I am using python to populate a table with the file pathways of a number of stored files. However the pathway needs to have the full network drive computer name not just the drive letter, ie

//ComputerName/文件夹/子文件夹/文件

//ComputerName/folder/subfolder/file

不是

P:/文件夹/子文件夹/文件

P:/folder/subfolder/file

我已经研究过使用win32api,win32file和os.path模块,但是看起来没有什么可以做到的.我需要类似win32api.GetComputerName()的东西,但是能够放入一个已知的驱动器盘符作为参数,并且它返回映射到该盘符的计算机名称.

I have investigated using the win32api, win32file, and os.path modules but nothing is looking like its able to do it. I need something like win32api.GetComputerName() but with the ability to drop in a known drive letter as an argument and it return the computer name that is mapped to the letter.

那么python中是否总有一个驱动器号并找回计算机名称?

So is there anyway in python to look up a drive letter and get back the computer name?

推荐答案

使用 WNetAddConnection2 创建网络驱动器.要获取与本地设备关联的远程路径,请调用 WNetGetConnection .您可以使用ctypes进行以下操作:

Network drives are mapped using the Windows Networking API that's exported by mpr.dll (multiple provider router). You can create a network drive via WNetAddConnection2. To get the remote path that's associated with a local device, call WNetGetConnection. You can do this using ctypes as follows:

import ctypes
from ctypes import wintypes

mpr = ctypes.WinDLL('mpr')

ERROR_SUCCESS   = 0x0000
ERROR_MORE_DATA = 0x00EA

wintypes.LPDWORD = ctypes.POINTER(wintypes.DWORD)
mpr.WNetGetConnectionW.restype = wintypes.DWORD
mpr.WNetGetConnectionW.argtypes = (wintypes.LPCWSTR,
                                   wintypes.LPWSTR,
                                   wintypes.LPDWORD)

def get_connection(local_name):
    length = (wintypes.DWORD * 1)()
    result = mpr.WNetGetConnectionW(local_name, None, length)
    if result != ERROR_MORE_DATA:
        raise ctypes.WinError(result)
    remote_name = (wintypes.WCHAR * length[0])()
    result = mpr.WNetGetConnectionW(local_name, remote_name, length)
    if result != ERROR_SUCCESS:
        raise ctypes.WinError(result)
    return remote_name.value

例如:

>>> subprocess.call(r'net use Y: \\live.sysinternals.com\tools')
The command completed successfully.
0
>>> print(get_connection('Y:'))
\\live.sysinternals.com\tools

这篇关于从python中的网络驱动器号获取完整的计算机名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆