Search code examples
unixftpscriptingreturn

Checking ftp return codes from Unix script


I am currently creating an overnight job that calls a Unix script which in turn creates and transfers a file using ftp. I would like to check all possible return codes. The man page for ftp doesn't list return codes. Does anyone know where to find a list? Anyone with experience with this? We have other scripts that grep for certain return strings in the log, and they send an email when in error. However, they often miss unanticipated codes. I am then putting the reason into the log and the email.


Solution

  • I think it is easier to run the ftp and check the exit code of ftp if something gone wrong.

    I did this like the example below:

    # ...
    ftp -i -n $HOST 2>&1 1> $FTPLOG << EOF
    quote USER $USER
    quote PASS $PASSWD
    cd $RFOLDER
    binary
    put $FOLDER/$FILE.sql.Z $FILE.sql.Z
    bye
    EOF
    
    # Check the ftp util exit code (0 is ok, every else means an error occurred!)
    EXITFTP=$?
    if test $EXITFTP -ne 0; then echo "$D ERROR FTP" >> $LOG; exit 3; fi
    if (grep "^Not connected." $FTPLOG); then echo "$D ERROR FTP CONNECT" >> $LOG; fi 
    if (grep "No such file" $FTPLOG); then echo "$D ERROR FTP NO SUCH FILE" >> $LOG; fi 
    if (grep "access denied" $FTPLOG ); then echo "$D ERROR FTP ACCESS DENIED" >> $LOG; fi
    if (grep "^Please login" $FTPLOG ); then echo "$D ERROR FTP LOGIN" >> $LOG; fi
    

    Edit: To catch errors I grep the output of the ftp command. But it's truly it's not the best solution.

    I don't know how familier you are with a Scriptlanguage like Perl, Python or Ruby. They all have a FTP module which you can be used. This enables you to check for errors after each command. Here is a example in Perl:

    #!/usr/bin/perl -w
    use Net::FTP;
    $ftp = Net::FTP->new("example.net") or die "Cannot connect to example.net: $@";
    $ftp->login("username", "password") or die "Cannot login ", $ftp->message;
    $ftp->cwd("/pub") or die "Cannot change working directory ", $ftp->message;
    $ftp->binary;
    $ftp->put("foo.bar") or die "Failed to upload ", $ftp->message;
    $ftp->quit;
    

    For this logic to work user need to redirect STDERR as well from ftp command as below

    ftp -i -n $HOST >$FTPLOG 2>&1 << EOF
    

    Below command will always assign 0 (success) as because ftp command wont return success or failure. So user should not depend on it

    EXITFTP=$?