在 Fabric 中,如何从远程路径创建 glob 列表

In Fabric how can I create a glob list from a remote path

使用 Python 的 Fabric 我想在远程服务器之间传输文件。

我需要从 **.txt 之类的 glob 表达式生成要传输的文件列表(然后再应用一些额外的排除项)。

对于传输远程的情况,很容易得到源文件列表,因为源是本地的:

[ f for f in Path(local_dir).glob(<my glob expression>)]

但是如何在远程服务器上执行此操作?我通过 with fabric.Connection(...) as c: 建立了到远程的连接,但我在连接对象中找不到 glob 方法。

一个选择是使用 c.sftp() to get a listing of all remote files, and then apply fnmatch.filter 返回的 SFTPClient 对象的 listdir 方法和你的 glob 表达式:

fnmatch.filter(c.sftp().listdir(), '*.py')

结果:具有以下远程目录,

$ ls
1.log  2.txt  3.py  4.csv  5.py

首先列出整个目录,然后使用 glob:

>>> c.sftp().listdir()
['5.py', '3.py', '4.csv', '2.txt', '1.log']
>>> fnmatch.filter(c.sftp().listdir(), '*.py')
['5.py', '3.py']