Logo Background

Retry SFTP Connection In Shell Script

  • By on July 14, 2010 | No Comments

    Looking for coding on retry SFTP connection in shell script? You can use this code to enable multiple attempts in case of errors such as network failure or remote server is down.

    Our existing shell script hit on different kind of SFTP error and one of it is ssh_exchange_identification: Connection closed by remote host.

    Connecting to 127.0.0.1...
    ssh_exchange_identification: Connection closed by remote host
    Connection closed

    This SFTP connection error might caused by the remote server is too busy, thus we need to implement the code to retry the SFTP connection in certain interval.

    We used the loopback interface 127.0.0.1 for the testing the retry SFTP connection in shell script.

    In this case, we specified the number of retries for SFTP connection failures as 10 and it will reconnect in each 60 second.

    The retry SFTP code should be in place before the shell script put or get file from remote server.

    At last, change the parameter in retry SFTP code based on your environment.

    #!/bin/bash
     
    SFTP_USER=username
    SFTP_SERVER=127.0.0.1
     
    # Ping To Check Remote Server Status
    ping $SFTP_SERVER
    if [ ${?} -ne 0 ]
    then
            echo "Unable to connect to destination server."
            exit 2
    fi
     
    ## Begin - Verify SFTP Connection On Remote Host ##
    echo -e "\n"
    echo "Begin - Verify SFTP Connection On Remote Host"
     
    SFTP_RETRY_COUNT=0
    SFTP_RETRY_SECOND=60
     
    while [ $SFTP_RETRY_COUNT != 10 ]
    do
     
    # Establish SFTP To Verify Connection To Staging Server
    SFTP_CONNECT=`sftp -o IdentityFile=$HOME/.ssh/$SFTP_USER $SFTP_USER@$SFTP_SERVER 
    << END 2> /tmp/sftp_error.log
    quit
    END`
     
    # Check Log File Exist Before Validation Start
    if [ -f /tmp/sftp_error.log ]
    then
     
            # Trap SFTP Connection Closed Error
            TRAP_SFTP_ERROR=`cat /tmp/sftp_error.log | grep "Connection closed"`
     
     
            if echo "$TRAP_SFTP_ERROR" | grep "Connection closed"
            then
                    echo "SFTP Connection Status: Fail"
                    SFTP_RETRY_COUNT=$[$SFTP_RETRY_COUNT+1]
                    echo "Retry SFTP Connection -" $SFTP_RETRY_COUNT
                    sleep $SFTP_RETRY_SECOND
     
                            if [ $SFTP_RETRY_COUNT == 10 ]
                            then
                                    echo "Maximum Retry Reached"
                            fi
     
            else
                    echo "SFTP Connection Status: Success"
                    SFTP_RETRY_COUNT=10
            fi
     
    fi
     
    done
     
    echo "End - Verify SFTP Connection On Remote Host"
    echo -e "\n"
    ## End - Verify SFTP Connection On Remote Host ##
    Previous
    Next
    » Unix Directory Permission Checking Script
Leave a Comment