Loop before connecting to SSH

Sometimes when connecting to a remote SSH server, I get Connection Closed By *IP*; Couldn't read packet: Connection reset by peer.

But after reusing one or two times, it connects correctly.

This poses a problem with several bash scripts that I use to automatically upload archived backups to the SSH server, for example:

export SSHPASS=$sshpassword
sshpass -e sftp -oBatchMode=no -b - root@$sshaddress << !
   cd $remotefolder
   put $backupfolder/Qt_$date.sql.gz
   bye
!

      

How can I get this part of the loop until it is properly connected?

UPDATE: (Solution)

RETVAL=1
while [ $RETVAL -ne 0 ]
do
export SSHPASS=$sshpassword
sshpass -e sftp -oBatchMode=no -b - root@$sshaddress << !
   cd $remotefolder
   put $backupfolder/Qt_$date.tgz
   bye
!
RETVAL=$?
[ $RETVAL -eq 0 ] && echo Success
[ $RETVAL -ne 0 ] && echo Failure
done

      

+3


source to share


2 answers


I'm not a shell scripting expert, but I would check the return value sshpass

when it exits.

From man ssh

:

ssh exits with the exit status of the remote command or
with 255 if an error occurred.

      

From man sshpath

:



Return values

As with any program, sshpass returns 0 on success. In case of failure, the following return codes are used:

  • Invalid command line argument
  • Conflicting arguments
  • General runtime error
  • Unrecognized response from ssh (parse error)
  • Invalid / incorrect password
  • The host's public key is unknown. sshpass exits without confirming the new key.

Also, ssh can complain about a person in the middle of an attack. This complaint does not go to tty. In other words, even with sshpass, the error message from ssh is printed with standard error. In such a case, the ssh return code is returned. This is usually the unimaginative (and uninformative) "255" for all error cases.

So, try running the command and check its return value. If the return value was not 0

(for SUCCESS

), try again. Repeat using a loop while

until you are successful.

Sidenote: why are you using public key authentication (no password)sshpass

instead ? It's more secure (you don't need to write down your password) and makes logging in with the usual ssh

one as easy as ssh username@host

.

There's even a simple tool to customize him ssh-copy-id

.

-1


source


Try something like this:

export SSHPASS=$sshpassword

sshpassFunc() {
    sshpass -e sftp -oBatchMode=no -b - root@$sshaddress << !
    cd $remotefolder
    put $backupfolder/Qt_$date.sql.gz
    bye
!
}

until sshpassFunc; do
    sleep 1
done

      



(not verified)

0


source







All Articles