How to capture the ftp error code in batch scripts?

13,692

Solution 1

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
)

Solution 2

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
)
Share:
13,692
Graviton
Author by

Graviton

A software developer.

Updated on June 23, 2022

Comments

  • Graviton
    Graviton almost 2 years

    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 that, 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?