Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort file list pulled from SFTP server using Paramiko by modification date?

I have this code that pulls files from a server using Paramiko. How can I get these files sorted by modification date?

ssh = paramiko.SSHClient()
# automatically add keys without requiring human intervention
ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() )

ssh.connect(sftpURL, username=sftpUser, password=sftpPass)

sftp = ssh.open_sftp()
filesInSFTP = sftp.listdir(sftpPullDirectory)
# Get only the XML and XLSX files
filesInSFTP = [file for file in filesInSFTP if file.lower().endswith(('.xml', '.xlsx'))]
like image 314
mastercool Avatar asked Oct 21 '25 17:10

mastercool


1 Answers

Retrieve the listing with file attributes (including the modification time) using SFTPClient.listdir_attr. And then sort the list by SFTPAttributes.st_mtime field.

filesInSFTP = sftp.listdir_attr(sftpPullDirectory)
filesInSFTP.sort(key = lambda f: f.st_mtime)

Related questions:

  • How to get the latest folder that contains a specific file of interest in Linux and download that file using Paramiko in Python?
  • Paramiko get sorted directory listing

Obligatory warning: Do not use AutoAddPolicy – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".

like image 158
Martin Prikryl Avatar answered Oct 23 '25 06:10

Martin Prikryl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!