python - 如何使用 Paramiko 从 SFTP 服务器下载最新文件?

标签 python sftp paramiko

我想编写连接到我大学 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() 

最佳答案

使用 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?

关于python - 如何使用 Paramiko 从 SFTP 服务器下载最新文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30626615/

相关文章:

python - 在 pandas 数据框中查找列相同的索引值

python - 如何更新 matplotlib 中的条形图?

python - 在 Python 中使用 SFTP 上传文件,但如果路径不存在则创建目录

python - 如何确保在杀死Python Paramiko脚本时所有生成的进程都消失了?

c# - 使用 SFTP 从 FTP 站点上传下载文件

python - Paramiko - sftp.get 下载空白文件

python - graph_tool osx 中缺少 graph_draw 吗?

python - 使用 openpyxl 将公式从一个单元格复制到另一个单元格

java - 无法在 ubuntu 18.04 中使用 apache commons vfs for vsftpd 重命名文件

SFTP 中出现 java.security.InvalidAlgorithmParameterException