【问题标题】:Loop through files in FTP directory using bat file使用bat文件循环FTP目录中的文件
【发布时间】:2013-09-24 21:38:26
【问题描述】:
我有一个批处理文件,由计划的 Windows 服务每 5 分钟执行一次。批处理文件针对特定文件掩码执行 mget:*.ext。
在 mget 之后,它会执行 mdel *.ext。
最近遇到一个问题:在执行mget和mdel之间创建文件z.ext时,该文件被删除但不在mget中。这当然是有道理的。
所以现在我正在寻找合适的 windows ftp 命令,这些命令将遍历文件并逐个文件执行 mget 和 mdel 文件。
这可能吗?
【问题讨论】:
标签:
windows
batch-file
ftp
【解决方案1】:
ftp scriptng 非常有限,但我认为你可以使用this approach。基本上,您必须运行 ftp 两次,第一次收集要下载的文件列表,然后第二次下载(并删除)每个文件(结合大量 cmd 脚本)您仍然没有得到任何错误处理和ftp 服务器的容错能力并不完全众所周知。
上面网站的相关例子是:
@Echo Off
REM -- Define File Filter, i.e. files with extension .txt
Set FindStrArgs=/E /C:".txt"
REM -- Extract Ftp Script to create List of Files
Set "FtpCommand=ls"
Call:extractFileSection "[Ftp Script 1]" "-">"%temp%\%~n0.ftp"
Rem Notepad "%temp%\%~n0.ftp"
REM -- Execute Ftp Script, collect File Names
Set "FileList="
For /F "Delims=" %%A In ('"Ftp -v -i -s:"%temp%\%~n0.ftp"|Findstr %FindStrArgs%"') Do (
Call Set "FileList=%%FileList%% "%%A""
)
REM -- Extract Ftp Script to download files that don't exist in local folder
Set "FtpCommand=mget"
For %%A In (%FileList%) Do If Not Exist "%%~A" Call Set "FtpCommand=%%FtpCommand%% "%%~A""
Call:extractFileSection "[Ftp Script 1]" "-">"%temp%\%~n0.ftp"
Rem Notepad "%temp%\%~n0.ftp"
For %%A In (%FtpCommand%) Do Echo.%%A
REM -- Execute Ftp Script, download files
ftp -i -s:"%temp%\%~n0.ftp"
Del "%temp%\%~n0.ftp"
GOTO:EOF
:extractFileSection StartMark EndMark FileName -- extract a section of file that is defined by a start and end mark
:: -- [IN] StartMark - start mark, use '...:S' mark to allow variable substitution
:: -- [IN,OPT] EndMark - optional end mark, default is first empty line
:: -- [IN,OPT] FileName - optional source file, default is THIS file
:$created 20080219 :$changed 20100205 :$categories ReadFile
:$source http://www.dostips.com
SETLOCAL Disabledelayedexpansion
set "bmk=%~1"
set "emk=%~2"
set "src=%~3"
set "bExtr="
set "bSubs="
if "%src%"=="" set src=%~f0& rem if no source file then assume THIS file
for /f "tokens=1,* delims=]" %%A in ('find /n /v "" "%src%"') do (
if /i "%%B"=="%emk%" set "bExtr="&set "bSubs="
if defined bExtr if defined bSubs (call echo.%%B) ELSE (echo.%%B)
if /i "%%B"=="%bmk%" set "bExtr=Y"
if /i "%%B"=="%bmk%:S" set "bExtr=Y"&set "bSubs=Y"
)
EXIT /b
[Ftp Script 1]:S
!Title Connecting...
open example.com
username
password
!Title Preparing...
cd public_html/MyRemoteDirectory
lcd c:\MyLocalDirectory
binary
hash
!Title Processing... %FtpCommand%
%FtpCommand%
!Title Disconnecting...
disconnect
bye
最好只在 python 或其他脚本环境中执行(假设您没有部署问题。)