首页 > 解决方案 > 如何在 Python 的 SMBCoonect listPath 函数中设置模式匹配

问题描述

SMBConnect 具有以下函数 listPath,它列出了给定目录的内容。

listPath(service_name, path, search=55, pattern='*', timeout=30) 检索路径中文件/文件夹的目录列表

参数:
service_name (string/unicode) – 路径的共享文件夹名称

path (string/unicode) – 相对于我们有兴趣了解其文件/子文件夹的 service_name 的路径。

search (integer) – 由 SMB_FILE_ATTRIBUTE_xxx 位的按位或组成的整数值(参见 smb_constants.py)。默认搜索值将查询所有只读、隐藏、系统、存档文件和目录。

pattern (string/unicode) -- 在返回客户端之前应用于结果的过滤器。

返回:
smb.base.SharedFile 实例的列表。

newConn=SMBConnection(arguments.username, password, DEFAULT_CLIENT_NAME, arguments.hostname, domain=arguments.domain,
            use_ntlm_v2=True, is_direct_tcp=True)
        assert newConn.connect(ip_address, 445, timeout=60)
        files = newConn.listPath('C$', '/' + 'testing', '*.pdf')
        for file in files:
            print(file.filename)

我无法让模式匹配更改为任何特定的内容。上面,我只想打印列表中包含“.pdf”的文件名。相反,当代码执行时,我只得到所有文件。没有错误或任何东西。我尝试过使用和不使用“*”和“。” 并得到相同的结果。

标签: pythonregexpython-3.x

解决方案


因此,我们通过使用与创建的 SMBConnection 对象一起使用的 this 的变体,让它与 re 类一起使用,作为 SMBConnection listPath 函数的变通方法。ListPath 函数仍在使用,但不是它的模式部分。我构建了一个“If-else”结构来处理 arg 输入和正则表达式。

扩展 = ['pdf', 'doc']
文件名 = ['foobar.pdf', 'bar.doc']
对于扩展中的扩展:
    已编译 = re.compile('\.{0}$'.format(extension))
    对于文件名中的文件名:
        结果 = re.search(编译,文件名)
        打印结果

推荐阅读