【问题标题】:How to download only the latest file from SFTP server with Paramiko?如何使用 Paramiko 从 SFTP 服务器只下载最新文件?
【发布时间】:2015-06-03 17:16:22
【问题描述】:

我想编写脚本连接到我的大学 SFTP 服务器并下载带有练习的最新文件。到目前为止,我已经对 Paramiko 示例中的代码进行了一些更改,但我不知道如何下载最新文件。

这是我的代码:

import functools
import paramiko 

class AllowAnythingPolicy(paramiko.MissingHostKeyPolicy):
    def missing_host_key(self, client, hostname, key):
        return

adress = 'adress'
username = 'username'
password = 'password'

client = paramiko.SSHClient()
client.set_missing_host_key_policy(AllowAnythingPolicy())
client.connect(adress, username= username, password=password)

def my_callback(filename, bytes_so_far, bytes_total):
    print ('Transfer of %r is in progress' % filename) 

sftp = client.open_sftp()
sftp.chdir('/directory/to/file')
for filename in sorted(sftp.listdir()):
    if filename.startswith('Temat'):
        callback_for_filename = functools.partial(my_callback, filename)
        sftp.get(filename, filename, callback=callback_for_filename)

client.close() 

【问题讨论】:

    标签: python sftp paramiko


    【解决方案1】:

    使用SFTPClient.listdir_attr 而不是SFTPClient.listdir 来获取带有属性的列表(包括文件时间戳)。

    然后,找到.st_mtime attribute最大的文件条目。

    代码如下:

    latest = 0
    latestfile = None
    
    for fileattr in sftp.listdir_attr():
        if fileattr.filename.startswith('Temat') and fileattr.st_mtime > latest:
            latest = fileattr.st_mtime
            latestfile = fileattr.filename
    
    if latestfile is not None:
        sftp.get(latestfile, latestfile)
    

    更复杂的例子见How to get the latest folder that contains a specific file of interest in Linux and download that file using Paramiko in Python?

    【讨论】:

    • 这对马丁很有帮助。谢谢!
    • 在网上搜索了几个小时后 - 这个答案非常适合我的问题,谢谢!
    【解决方案2】:
    import paramiko
    remote_path = '/tmp'
    
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_client.connect(hostname=<IP>, username=<USER>, password=<PW>,allow_agent=False)
    sftp_client = ssh_client.open_sftp()
    
    sftp_client.chdir(remote_path)
    for f in sorted(sftp_client.listdir_attr(), key=lambda k: k.st_mtime, reverse=True):
        sftp_client.get(f.filename, f.filename)
        break
    
    sftp_client.close()
    ssh_client.close()
    
    

    这将使用密码 (PW) 作为用户 (USER) 连接到远程服务器 (IP) 并下载 下的最新文件

    【讨论】:

    • 虽然此代码可以回答问题,但提供有关 如何 和/或 为什么 解决问题的附加上下文将改善答案的长期价值。
    • 已更新,ftp_client 只是一个变量名,但重命名为 stfp_client 以避免混淆,干杯!