【问题标题】:How to sync only the changed files from the remote directory using pysftp?如何使用 pysftp 仅同步远程目录中更改的文件?
【发布时间】:2018-05-07 15:07:19
【问题描述】:

我正在使用 pysftp 库的 get_r 函数 (https://pysftp.readthedocs.io/en/release_0.2.9/pysftp.html#pysftp.Connection.get_r) 从 sftp 服务器获取目录结构的本地副本。

对于远程目录的内容已更改并且我只想获取自上次运行脚本以来更改的文件的情况,这是正确的方法吗?

脚本应该能够递归同步远程目录并镜像远程目录的状态 - f.e.带有一个参数,用于控制是否应删除本地过时文件(远程服务器上不再存在的文件),以及是否应获取对现有文件和新文件的任何更改。

My current approach is here.

示例用法:

from sftp_sync import sync_dir

sync_dir('/remote/path/', '/local/path/')

【问题讨论】:

    标签: python synchronization sftp data-synchronization pysftp


    【解决方案1】:

    使用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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-05
      • 2019-01-23
      相关资源
      最近更新 更多