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

时间:2019-05-24 07:37:20

标签: python sftp paramiko pysftp

我在此站点上获得了一个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天的文件。

1 个答案:

答案 0 :(得分:3)

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

基于: