根据文件名中的时间戳从SFTP服务器下载最新文件

2024-05-15 09:06:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取远程Linux服务器目录中的最新文件。SFTP服务器中的文件每4小时创建一次,文件的特定名称以filegen_date_hour.json开头,如下例所示。在这种情况下,需要将最新文件“filegen_20200101_0800.json”传输到我的本地目录

filegen_20200101_0000.json
filegen_20200101_0400.json
filegen_20200101_0800.json

我在下面使用了Python 3代码,但出现了错误

latestFile = max(listFile, key=os.path.getctime)
ValueError: max() arg is an empty sequence

下面是SFTP代码

myHostname = "192.168.100.10"
myUsername = "user"
myPassword = "password"

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None

with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword, cnopts=cnopts) as sftp:
    with sftp.cd('/home/operation/genfiles/'):             
        fileDir = '/home/operation/genfiles/filegen_*.json' 
        **#file have specific pattern with filegen_*.json**
        listFile = glob.glob(fileDir)
        latestFile = max(listFile, key=os.path.getctime)
        sftp.get(latestFile)         

感谢您在这件事上的帮助。感谢您的回复和帮助


Tags: 文件key代码服务器目录jsonoswith
1条回答
网友
1楼 · 发布于 2024-05-15 09:06:10

首先,不能使用glob列出SFTP服务器上的文件。glob不会神奇地开始查询SFTP服务器,因为您之前已经打开了一个SFTP连接。它仍将查询本地文件系统

使用pysftp^{}。虽然它不支持通配符,但您必须在本地筛选所需的文件。像这里:
List files on SFTP server matching wildcard in Python using Paramiko


只有这样,您才能尝试查找最新的文件。 通常,您可以使用文件修改时间,如下所示:
How to download only the latest file from SFTP server with Paramiko?
代码用于ParamikoSFTPClient.listdir_attr,但Pystp^{}的代码相同

但在您的情况下,我不确定您是否可以依赖修改时间戳。看起来您实际上想要在文件名中使用时间戳。使用文件名格式,您只需按字典顺序选择最后一个文件

import fnmatch

...

with sftp.cd('/home/operation/genfiles'):             
    files = []
    for filename in sftp.listdir():
        if fnmatch.fnmatch(filename, "filegen_*.json"):
            files.append(filename)
    latestFile = max(files)

强制性警告:不要设置cnopts.hostkeys = None,除非您不关心安全性。有关正确的解决方案,请参见Verify host key with pysftp

相关问题 更多 >