开发者

How to capture the ftp error code in batch scripts?

I have a somewhat related, but different questions here.

I have a batch script (*.bat file) such as this:

@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

Basically this is a script that uploads a zip file to a ftp site. My question is t开发者_高级运维hat, the upload operation can fail from time to time ( the remote ftp is not available, "myfile.zip" is non-existent, upload operation interrupted and whatnot), and when such unfortunate things happen, I want my bat file return 1 ( exit 1).

It would be great if my upload wasn't successful, the ftp would throw an exception ( yes, like exception in C++), and I would have a catch-all exception that catches it and then exit 1, but I don' think this is available in batch script.

What is the best way to do what I need here?


You can redirect the output to a log file and when the ftp session is finished the file can be parsed.

@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
)


Windows FTP does not return any codes.

I suggest running a batch file that echo your ftp commands to a input response file, then use this file as input to the ftp command, redirecting stderr to a file and verifying the file size. something like this

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
)


Your only option in batch files that I know of is to use the "IF ERRORLEVEL" syntax, which requires your ftp client to return a non-zero error code.

http://www.robvanderwoude.com/errorlevel.php is a good reference guide.

Unfortunately I do not if the standard Windows ftp client returns non-zero error codes, so you may have to code your own if this is a requirement. This link suggests that it does not return an error code, but provides a work around albeit clunky, by redirecting the output to a file and using the FIND command to return an error code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜