Skip to content Skip to sidebar Skip to footer

How To Sync Only The Changed Files From The Remote Directory Using Pysftp?

I am using pysftp library's get_r function (https://pysftp.readthedocs.io/en/release_0.2.9/pysftp.html#pysftp.Connection.get_r) to get a local copy of a directory structure from sf

Solution 1:

Use the pysftp.Connection.listdir_attr to get file listing with attributes (including the file timestamp).

Then, iterate the list and compare against local files.

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():
        ifnot stat.S_ISDIR(f.st_mode):
            print("Checking %s..." % f.filename)
            local_file_path = os.path.join(local_path, f.filename)
            if ((notos.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)

Post a Comment for "How To Sync Only The Changed Files From The Remote Directory Using Pysftp?"