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/folder/subfolder/file

not

P:/folder/subfolder/file

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.

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

解决方案

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

For example:

>>> subprocess.call(r'net use Y: \\live.sysinternals.com\tools')

The command completed successfully.

0

>>> print(get_connection('Y:'))

\\live.sysinternals.com\tools

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值