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

时间:2011-08-23 08:40:31

标签: ftp batch-file

我有一些相关但不同的问题here

我有一个批处理脚本(*.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 ++中的异常一样),而且我会有一个抓住它的所有异常,然后exit 1,但我不认为这是批处理脚本。

在这里做我需要的最好方法是什么?

3 个答案:

答案 0 :(得分:2)

您可以将输出重定向到日志文件,当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 :(得分:0)

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

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

不幸的是,如果标准Windows ftp客户端返回非零错误代码,我不会这样做,因此如果需要,您可能需要编写自己的代码。 This link表明它不返回错误代码,但通过将输出重定向到文件并使用FIND命令返回错误代码,提供了一种尽管很笨拙的工作。

答案 2 :(得分:0)

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
)
相关问题