Search code examples
pythonpython-3.xpysftp

store file names of files present on SFTP server in list


I got a code to download 5 days older files from SFTP server. But instead of downloading the files, I want to store the names of 5 days older files into a list. Please help me to modify the code. Thanks in advance

Code I am using right now (based on Download files from SFTP server that are older than 5 days using Python)

import time

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir_attr(remotedir):
        remotepath = remotedir + "/" + entry.filename
        localpath = os.path.join(localdir, entry.filename)
        mode = entry.st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath)
            except OSError:     
                pass
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            if (time.time() - entry.st_mtime) // (24 * 3600) >= 5:
                sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

Solution

  • instead of using sftp.get to download the files, I'm just adding their path to a list, and returning it at the end

    import time
    
    def get_r_portable(sftp, remotedir):
        result = []
        for entry in sftp.listdir_attr(remotedir):
            remotepath = remotedir + "/" + entry.filename
            mode = entry.st_mode
            if S_ISDIR(mode):
                result += get_r_portable(sftp, remotepath)
            elif S_ISREG(mode):
                if (time.time() - entry.st_mtime) // (24 * 3600) >= 5:
                    result.append(entry.filename)
        return result