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?
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
source to share
I'm not a shell scripting expert, but I would check the return value
when it exits.
ssh exits with the exit status of the remote command or with 255 if an error occurred.
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
), try again. Repeat using a loop
until you are successful.
Sidenote: why are you using public key authentication (no password)
instead ? It's more secure (you don't need to write down your password) and makes logging in with the usual
one as easy as
source to share