使用 Paramiko 在 Python 中列出与通配符匹配的 SFTP 服务器上的文件

List files on SFTP server matching wildcard in Python using Paramiko

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('hostname', username='test1234', password='test')
path = ['/home/test/*.txt', '/home/test1/*.file', '/home/check/*.xml']
for i in path:

    for j in glob.glob(i):

        print j

client.close()

我正在尝试使用 glob.glob 列出远程服务器上的通配符文件。但是 glob.glob() 不起作用。

使用 Python 2.6.

远程服务器包含这些文件:/home/test1/check.file/home/test1/validate.file/home/test1/vali.file

任何人都可以帮助解决这个问题。

glob 不会神奇地开始使用远程服务器,只是因为您之前已经实例化了 SSHClient

你必须使用 Paramiko API 来列出文件,例如 SFTPClient.listdir:

import fnmatch
sftp = client.open_sftp()

for filename in sftp.listdir('/home/test'):
    if fnmatch.fnmatch(filename, "*.txt"):
        print filename

如果更符合您的需要,您也可以使用正则表达式进行匹配。参见


旁注:不要使用 AutoAddPolicy。你 这样做会失去安全感。参见 Paramiko "Unknown Server"

或者使用 pysftp 这是 paramiko 包装器并编写如下内容:

import pysftp


def store_files_name(fname):
    pass


def store_dir_name(dir_name):
    pass


def store_other_file_type(other_file):
    pass

with pysftp.Connection('server', username='user', password='pass') as sftp:
    sftp.walktree('.', store_files_name, store_dir_name, store_other_file_type)