【问题标题】:Download the latest file according to timestamp in file name from SFTP server根据文件名中的时间戳从 SFTP 服务器下载最新文件
【发布时间】:2020-08-05 02:35:05
【问题描述】:

我正在尝试在远程 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)         

感谢您对此事的帮助。感谢您的回复和帮助。

【问题讨论】:

    标签: python sftp paramiko pysftp


    【解决方案1】:

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

    使用 pysftp Connection.listdir。虽然它不支持通配符,所以你必须在本地过滤你想要的文件。喜欢这里:
    List files on SFTP server matching wildcard in Python using Paramiko


    只有这样您才能尝试查找最新的文件。 一般来说,您可以使用文件修改时间,如下所示:
    How to download only the latest file from SFTP server with Paramiko?
    代码是 Paramiko SFTPClient.listdir_attr 的代码,但它与 pysftp Connection.listdir_attr 相同。

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 2022-06-18
      • 2015-07-27
      • 2018-03-21
      • 1970-01-01
      相关资源
      最近更新 更多