我在此站点上有一个 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
from stat import S_ISDIR, S_ISREG
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)
但请注意 pysftp 似乎已经死了。考虑使用 Paramiko 代替。它具有几乎相同的 API,因此上面的代码几乎可以按原样工作(除了 Paramiko 没有 preserve_mtime
参数)。另请参阅pysftp vs. Paramiko .
基于:
关于python - 使用 Python 从 SFTP 服务器下载超过 5 天的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56287892/