如何用Bat脚本从远程FTP服务器查找符合规则的最新可用日志文件
问题描述
我有一个.bat脚本,用于连接FTP服务器并搜索文件。该FTP目录中的文件按周存储,命名规则为:当前年份+当前年份内的周数.LOG,例如:202310.LOG。我的脚本通过拼接当前年份和周数生成文件名(如202310.LOG),以此尝试获取存储在服务器上的最新文件。
如果最新的文件尚未上传(即不存在202310.LOG),我希望获取上一个可用的文件(例如若202309.LOG和202308.LOG都存在,则获取最新的202309.LOG),以便读取其元数据查看文件的新旧程度。示例代码如下:
set filename=GetCurrentYEar()GetCurrentWeek().LOG rem Imagine filename value is: 202310.LOG IF(filename does not exists) ( rem Then look for the latest filename(which seemingly is 202309.LOG or 202308.LOG if both of these exists, just get me latest one that is 202309.LOG) < %filename% )
我原本考虑使用for循环遍历目录中的文件逐一检查,但不知道如何在远程FTP服务器上实现这一点,请问有什么解决思路?
解决思路
方法1:从当前周数递减检查(最直接)
- 先获取当前年份和周数,生成初始文件名
- 编写循环逻辑,每次将周数减1(注意跨年情况:如果周数是1,年份减1,周数设为当年最后一周,比如2024年第1周的前一周是2023年第52周)
- 每次递减后生成新的文件名,通过FTP的
SIZE命令检查文件是否存在(SIZE 文件名返回213开头的响应说明存在,返回550说明不存在) - 一旦找到存在的文件,立即停止循环并使用该文件名
核心代码片段:
@echo off setlocal enabledelayedexpansion rem 通过PowerShell获取当前年份和周数 for /f %%a in ('powershell -Command "(Get-Date).Year"') do set "year=%%a" for /f %%a in ('powershell -Command "(Get-Date).WeekOfYear"') do set "week=%%a" :check_file rem 格式化周数为两位数字(如9转为09) if %week% lss 10 set "week=0%week%" set "filename=%year%%week%.LOG" rem 生成FTP指令并执行,检查文件是否存在 echo open ftp.example.com> temp.ftp echo your_username>> temp.ftp echo your_password>> temp.ftp echo SIZE %filename%>> temp.ftp echo quit>> temp.ftp ftp -s:temp.ftp> ftp_result.txt rem 检查响应是否包含213(文件存在标识) findstr /c:"213" ftp_result.txt >nul if not errorlevel 1 ( echo 找到可用文件:%filename% goto :cleanup ) else ( echo 文件%filename%不存在,尝试上一周 rem 处理周数递减与跨年逻辑 set /a week=%week%-1 if !week! equ 0 ( set /a year=%year%-1 for /f %%a in ('powershell -Command "(Get-Date -Year %year% -Month 12 -Day 31).WeekOfYear"') do set "week=%%a" ) goto :check_file ) :cleanup del temp.ftp ftp_result.txt endlocal
方法2:获取FTP目录列表后本地筛选
- 通过FTP的
NLST命令获取远程目录下所有.LOG文件列表,保存到本地文本文件 - 用
findstr过滤出符合YYYYWW.LOG格式的文件 - 对筛选后的文件按名称降序排序(文件名本身是年份+周数,降序后第一个就是最新可用文件)
- 直接取排序后的第一个文件作为目标
核心代码片段:
@echo off setlocal enabledelayedexpansion rem 获取FTP目录下的.LOG文件列表 echo open ftp.example.com> temp.ftp echo your_username>> temp.ftp echo your_password>> temp.ftp echo NLST *.LOG>> temp.ftp echo quit>> temp.ftp ftp -s:temp.ftp> file_list.txt rem 过滤出符合命名规则的文件 findstr /r "^[0-9][0-9][0-9][0-9][0-9][0-9]\.LOG$" file_list.txt> filtered_list.txt rem 降序排序后取第一个文件 for /f "tokens=1" %%a in ('sort /r filtered_list.txt') do ( set "latest_file=%%a" goto :found ) :found echo 最新可用文件:!latest_file! rem 后续处理逻辑 :cleanup del temp.ftp file_list.txt filtered_list.txt endlocal
注意事项
- 周数必须格式化为两位数字,避免生成
20239.LOG这类不符合规则的文件名 - 跨年场景需特殊处理,确保能正确定位到上一年的最后一周
- FTP执行结果可能包含冗余信息,需用
findstr过滤有效内容 - 脚本中的FTP地址、用户名、密码需替换为实际信息,敏感信息建议用环境变量存储
内容的提问来源于stack exchange,提问作者Retrosec6
相关产品推荐
相关产品推荐

