pysmb 获取 smb 共享服务器的目录树

pin*_*nky 2 python linux samba os.walk

我设法使用 pysmb 连接和访问 smb 共享服务器。我的意思是从服务器读取/写入/删除/创建文件/文件夹。

大多数情况下,我需要根据 smb 设备和服务名称(pysmb 术语)从服务器读取文件(无论是 jpg 还是 csv 等)。

基本上我不知道 smb 设备中的文件名和目录名是什么。这意味着命名是动态的。

我想知道在处理读取文件之前先获取过滤的目录树是个好主意。文件和目录的数量未知,大约 3 个月的数据约为 60TB。

listShares(timeout=30)[source]
listPath(service_name, path, search=55, pattern='*', timeout=30)
Run Code Online (Sandbox Code Playgroud)

上述方法仅获得层次结构的 1 个特定级别。我想要的是类似的输出os.walk.path()

有人有想法的经验吗?我能得到建议吗?非常感谢您。

Roh*_*t.M 5

不确定这是否是您想要的。但我正在研究类似的东西,所以你就开始吧。

我使用 Impacket,它实际上使用 pysmb 中的一些基类。 https://github.com/CoreSecurity/impacket

我希望您的 listPath 方法以文本格式返回输出,而不是 SharedFile 实例。

我的意思是,在列出它们时存储以下值。

get_longname is_directory get_filesize

我有树方法,它遍历共享/路径并检查 SharedFile 实例是否是目录,并对自身进行递归调用。

def tree(self, path):    
   for x in range(0, path.count('\\')):
            print '|  ',
    print '%s' % os.path.basename(path.replace('\\', '/'))

    self.do_ls('%s\\*' % path, pretty=False) #Stores files data in listdata[]

    for file, is_directory, size in self.listdata:
            if file in ('.', '..'):
                continue
            if is_directory > 0:
                self.tree(ntpath.join(path, file))
            else:
                for x in range(0, path.count('\\')):
                    print '|  ',
                print '|-- %s (%d bytes)' % (file, size)


>>>d.tree('test')
.snapshot
|   hourly.0
|   |   dir0
|   |   |   Test051-89
|   |   |   Test051_perf3100-test_43
|   |   |   |   Test051_perf3100-test_52
|   |-- a.txt (8 bytes)
|   |-- dir0 - Shortcut.lnk (1834 bytes)
|   |-- Thumbs.db (46080 bytes)
|   |   20743
|   |   |-- file.txt (82 bytes)
|   |   |-- link.txt (82 bytes)
|   |   |   targetdir
|   |   |   |-- file2.txt (39 bytes)
|   |-- target.txt (6394368 bytes)
|   |   linkdir
|   |   |-- file2.txt (39 bytes)
Run Code Online (Sandbox Code Playgroud)


pin*_*nky 5

def smbwalk(conn, shareddevice, top = u'/'):
    dirs , nondirs = [], []

    if not isinstance(conn, SMBConnection):
        raise TypeError("SMBConnection required")


    names = conn.listPath(shareddevice, top)

    for name in names:
        if name.isDirectory:
            if name.filename not in [u'.', u'..']:
                dirs.append(name.filename)
        else:
            nondirs.append(name.filename)

    yield top, dirs, nondirs

    for name in dirs:
        new_path = os.path.join(top, name)
        for x in smbwalk(conn, shareddevice, new_path):
            yield x


conn = SMBConnection(*con_str, domain='workgroup')
assert conn.connect('10.10.10.10')
ans = smbwalk(conn, 'SHARE_FOLDER',top= '/')
Run Code Online (Sandbox Code Playgroud)

这就是我想要的,但我发现如果网络共享太大,返回需要很长时间。