我正在使用 pysftp 库的 get_r 函数 ( https://pysftp.readthedocs.io/en/release_0.2.9/pysftp.html#pysftp.Connection.get_r ) 从 sftp 服务器获取目录结构的本地副本。
当远程目录的内容发生变化并且我只想获取自上次脚本运行以来发生变化的文件时,这是正确的方法吗?
该脚本应该能够递归同步远程目录并镜像远程目录的状态 - f.e.使用参数控制是否应删除本地过时文件(那些不再存在于远程服务器上的文件),以及是否应获取对现有文件和新文件的任何更改。
示例用法:
from sftp_sync import sync_dir
sync_dir('/remote/path/', '/local/path/')
请您参考如下方法:
使用 pysftp.Connection.listdir_attr获取具有属性的文件列表(包括文件时间戳)。
然后,迭代列表并与本地文件进行比较。
import os
import pysftp
import stat
remote_path = "/remote/path"
local_path = "/local/path"
with pysftp.Connection('example.com', username='user', password='pass') as sftp:
sftp.cwd(remote_path)
for f in sftp.listdir_attr():
if not stat.S_ISDIR(f.st_mode):
print("Checking %s..." % f.filename)
local_file_path = os.path.join(local_path, f.filename)
if ((not os.path.isfile(local_file_path)) or
(f.st_mtime > os.path.getmtime(local_file_path))):
print("Downloading %s..." % f.filename)
sftp.get(f.filename, local_file_path)
尽管现在,您不应该使用 pysftp,因为它已经死了。而是直接使用 Paramiko。参见 pysftp vs. Paramiko .上面的代码也适用于 Paramiko 及其 SFTPClient.listdir_attr。 .
