使用Python从SFTP服务器下载超过5天的文件

我在这个站点上有一个Python脚本,它从SFTP服务器下载目录中的文件.现在我需要帮助来修改此代码,以便它只下载从使用代码之日起超过5天的文件.

下载文件的代码(基于Python pysftp get_r from Linux works fine on Linux but not on Windows):

import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None    
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir(remotedir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        mode = sftp.stat(remotepath).st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath,mode=777)
            except OSError:     
                pass
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

remote_path=input("enter the remote_path: ")
local_path=input("enter the local_path: ")

get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)

请帮我修改代码,以便它只从当天下载5天后下载文件.

解决方法:

使用pysftp.Connection.listdir_attr获取包含属性的文件列表(包括文件时间戳).

然后,迭代列表并仅选择所需的文件.

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)

虽然代码可以更简单,但如果您不需要递归下载:

for entry in sftp.listdir_attr(remotedir):
    mode = entry.st_mode
    if S_ISREG(mode) and ((time.time() - entry.st_mtime) // (24 * 3600) >= 5):
       remotepath = remotedir + "/" + entry.filename
       localpath = os.path.join(localdir, entry.filename)
       sftp.get(remotepath, localpath, preserve_mtime=True)

基于:

> Python pysftp get_r from Linux works fine on Linux but not on Windows
(我已更新此代码源以使用listdir_attr,因为它更有效)
> How to sync only the changed files from the remote directory using pysftp?
> Delete files that are older than 7 days

上一篇:linux-将多个SFTP命令行转换为单行命令行


下一篇:java – 使用JSCH在远程服务器上获取MD5校验和