Search code examples
pythonsftpparamiko

Paramiko Python. How can i get the last modified file on the SFTP?


I need to get the last modified file's name using paramiko

client.connect(hostname=server["host"], username=server["user"], pkey=pkey, allow_agent=False, look_for_keys=False)
    
sftp = client.open_sftp()
print("Connected!")

I don't know how to proceed from here!

I tried:

utime = sftp.stat("path").st_mtime
last_modified = datetime.fromtimestamp(utime)

print(last_modified)

someone can help me?


Solution

  • Get the list of files in 'path' and find the one with the greatest modified time:

    last_modified = max(
        sftp.listdir_attr('path'),
        key=lambda f.st_mtime
    )
    print(last_modified.filename)
    

    edit: Changed listdir()/stat() to listdir_attr() because it's more efficient. According to this answer listdir() calls listdir_attr() and throws away everything but the filename.


    If you need to filter out the directories:

    from stat import S_ISREG
    last_modified = max(
        filter(lambda f: S_ISREG(f.st_mode), sftp.listdir_attr('path')),
        key=lambda f: f.st_mtime
    )
    print(last_modified.filename)