是否有可能从python获取给定远程Windows主机的共享目录列表? 我在我的HOMEGROUP中有机器,让我们说:COMP并且有共享目录“Users”。 在Python中,我可以使用
列出文件os.listdir(r"\\COMP\Users")
但我想知道共享的文件夹,例如用户。
答案 0 :(得分:1)
您可以致电NetShareEnum
列出所有STYPE_DISKTREE
个股票,包括隐藏的股票,例如“ADMIN $”和“C $”。
import ctypes
from ctypes import wintypes
netapi32 = ctypes.WinDLL('netapi32')
STYPE_DISKTREE = 0x00000000
STYPE_PRINTQ = 0x00000001
STYPE_DEVICE = 0x00000002
STYPE_IPC = 0x00000003
STYPE_MASK = 0x000000FF
STYPE_TEMPORARY = 0x40000000
STYPE_SPECIAL = 0x80000000
MAX_PREFERRED_LENGTH = 0xFFFFFFFF
ERROR_MORE_DATA = 0x00EA
class NET_API_BUFFER(ctypes.Structure):
pass
class SHARE_INFO(NET_API_BUFFER):
pass
class SHARE_INFO_1(SHARE_INFO):
_fields_ = (('shi1_netname', wintypes.LPWSTR),
('shi1_type', wintypes.DWORD),
('shi1_remark', wintypes.LPWSTR))
LPNET_API_BUFFER = ctypes.POINTER(NET_API_BUFFER)
class LPSHARE_INFO(LPNET_API_BUFFER):
_type_ = SHARE_INFO
class LPSHARE_INFO_1(LPSHARE_INFO):
_type_ = SHARE_INFO_1
LPLPSHARE_INFO = ctypes.POINTER(LPSHARE_INFO)
if not hasattr(wintypes, 'LPBYTE'): # 2.x
wintypes.LPBYTE = ctypes.POINTER(wintypes.BYTE)
if not hasattr(wintypes, 'LPDWORD'): # 2.x
wintypes.LPDWORD = ctypes.POINTER(wintypes.DWORD)
netapi32.NetShareEnum.argtypes = (
wintypes.LPWSTR, # _In_ servername
wintypes.DWORD, # _In_ level
LPLPSHARE_INFO, # _Out_ bufptr
wintypes.DWORD, # _In_ prefmaxlen
wintypes.LPDWORD, # _Out_ entriesread
wintypes.LPDWORD, # _Out_ totalentries
wintypes.LPDWORD) # _Inout_ resume_handle
netapi32.NetApiBufferFree.argtypes = (
LPNET_API_BUFFER,) # _In_ Buffer
def list_shares(server_name):
pshare_info = LPSHARE_INFO_1()
entries_read = wintypes.DWORD()
total_entries = wintypes.DWORD()
resume_handle = wintypes.DWORD()
shares = []
while True:
result = netapi32.NetShareEnum(server_name,
1,
ctypes.byref(pshare_info),
MAX_PREFERRED_LENGTH,
ctypes.byref(entries_read),
ctypes.byref(total_entries),
ctypes.byref(resume_handle))
if result and result != ERROR_MORE_DATA:
raise ctypes.WinError(result)
try:
for i in range(entries_read.value):
info = pshare_info[i]
if info.shi1_type & STYPE_MASK == STYPE_DISKTREE:
shares.append(info.shi1_netname)
finally:
free_result = netapi32.NetApiBufferFree(pshare_info)
if free_result:
raise ctypes.WinError(free_result)
if result != ERROR_MORE_DATA:
break
return shares
示例:
if __name__ == '__main__':
import sys
if len(sys.argv) > 1:
server_name = sys.argv[1]
else:
server_name = '127.0.0.1'
print('\n'.join(sorted(list_shares(server_name))))
答案 1 :(得分:0)
您可以尝试使用PySMB。使用方法listShares。