使用Python Paramiko从SFTP服务器通过通配符下载文件
解决SFTP通配符匹配下载文件的问题
嘿,你遇到的这个问题很常见——Paramiko的SFTP.get()方法本身并不直接支持通配符(比如*),所以直接写/Home/user/Automation_*.csv是行不通的。不过我们可以通过先获取远程目录的文件列表,再筛选出符合模式的文件来解决这个问题,甚至还能自动选择最新的那个带时间戳的文件,具体步骤如下:
实现思路
- 先列出远程目标目录下的所有文件
- 使用
fnmatch模块匹配符合Automation_*.csv模式的文件 - (可选)如果有多个匹配文件,按时间戳排序选出最新的那个
- 下载选中的文件
修改后的完整代码
import paramiko import os import fnmatch from stat import S_ISREG paramiko.util.log_to_file('logfile.log') # SFTP连接信息 host = "ftp.servername.com" port = 22 username = "myuser" password = "mypass" # 远程目录和文件匹配模式 remote_dir = '/Home/user/' file_pattern = 'Automation_*.csv' localpath = 'file/dkc.csv' try: # 建立SFTP连接 transport = paramiko.Transport((host, port)) transport.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(transport) # 获取远程目录下的所有文件(只筛选普通文件,排除目录) remote_files = [] for entry in sftp.listdir_attr(remote_dir): if S_ISREG(entry.st_mode): # 判断是否为普通文件 remote_files.append(entry) # 匹配符合模式的文件 matched_files = [entry for entry in remote_files if fnmatch.fnmatch(entry.filename, file_pattern)] if not matched_files: print("没有找到符合模式的文件!") else: # 按文件修改时间排序,取最新的那个(如果有多个的话) matched_files.sort(key=lambda x: x.st_mtime, reverse=True) latest_file = matched_files[0].filename remote_filepath = os.path.join(remote_dir, latest_file) # 下载文件 print(f"开始下载文件: {remote_filepath}") sftp.get(remote_filepath, localpath) print("下载完成!") finally: # 确保连接关闭 if 'sftp' in locals() and sftp is not None: sftp.close() if 'transport' in locals() and transport is not None: transport.close()
代码说明
fnmatch模块:专门用来做文件名的通配符匹配,和shell的通配符规则一致listdir_attr():相比listdir(),它能获取文件的元数据(比如修改时间、文件类型),方便我们筛选文件和排序- 文件排序:通过
st_mtime(文件修改时间)倒序排序,确保我们下载的是最新生成的那个带时间戳的文件 - 异常处理:用
try...finally确保即使出错,SFTP连接也能正常关闭
这样修改后,不管远程文件的时间戳后缀是什么,只要符合Automation_*.csv的格式,就能自动匹配并下载最新的那个文件啦!
内容的提问来源于stack exchange,提问作者Vishwanatha Jois
相关产品推荐
相关产品推荐

