如何在批处理脚本中捕获FTP错误代码?

6

我有一个有些相关但又不同的问题,这里

我有一个批处理脚本(*.bat文件),如下所示:

@ftp -i -s:"%~f0"&GOTO:EOF
open ftp.myhost.com
myuser
mypassword
!:--- FTP commands below here ---
lcd "C:\myfolder"
cd  /testdir
binary
put "myfile.zip"
disconnect
bye

基本上,这是一个将 zip 文件上传到 ftp 网站的脚本。我的问题是,上传操作有时会失败(远程 ftp 不可用,"myfile.zip" 不存在,上传操作中断等),当发生这种不幸的事情时,我希望我的批处理文件返回 1(exit 1)。
如果我的上传不成功,那么 ftp 应该会抛出异常(是的,就像 C++ 中的异常),然后我会有一个 catch-all 异常来捕获它,然后退出(exit 1),但我认为在批处理脚本中没有这个功能。
如何最好地实现我需要的内容?
3个回答

3

您可以将输出重定向到日志文件,当ftp会话结束时,可以解析该文件。

@ftp -i -s:"%~f0" > log.txt & GOTO :parse
open ftp.myhost.com
myuser
mypassword
!:--- FTP commands below here ---
lcd "C:\myfolder"
cd  /testdir
binary
put "myfile.zip"
disconnect
bye

:parse
for /F "delims=" %%L in (log.txt) Do (
  ... parse each line
)

1

Windows FTP没有返回任何代码。

我建议运行一个批处理文件,将您的ftp命令回显到一个输入响应文件中,然后将此文件用作ftp命令的输入,将stderr重定向到一个文件并验证文件大小。像这样:

echo open ftp.myhost.com >ftpscript.txt
echo myuser >>ftpscript.txt
echo mypassword >>ftpscript.txt
echo lcd "C:\myfolder"  >>ftpscript.txt
echo cd  /testdir  >>ftpscript.txt
echo binary  >>ftpscript.txt
echo put "myfile.zip"  >>ftpscript.txt
echo disconnect  >>ftpscript.txt
echo bye  >>ftpscript.txt

ftp -i -s:ftpscript.txt >ftpstdout.txt 2>ftpstderr.txt 
rem check the ftp error file size, if 0 bytes in length then there was no erros
forfiles /p . /m ftpstderr.txt /c "cmd /c if @fsize EQU 0 del /q ftpstderr.txt"
if EXIST ftpstderr.txt (
   exit 1
)

0

在批处理文件中,我所知道的唯一选项是使用“IF ERRORLEVEL”语法,这需要您的ftp客户端返回非零错误代码。

http://www.robvanderwoude.com/errorlevel.php 是一个很好的参考指南。

不幸的是,我不知道标准的Windows ftp客户端是否返回非零错误代码,因此如果这是一个要求,您可能需要编写自己的代码。 此链接 表示它不返回错误代码,但提供了一个笨拙的解决方法,通过将输出重定向到文件并使用FIND命令返回错误代码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接