Bash Script to test SSH connection for rsync

Automating the backup task play an important role in IT Infrastructure management. Nowadays lot of commercial backup software’s are available to us. Choosing the right software backup solution is so important since you’ll have to live with it daily and must be a reliable one to your needs. But price can be a concern here. More features available, means more price. So people especially folks here at TechDire are obviously look for open source Backup Solutions. I should say “Bacula” is a fantastic open source backup tool. Its first choice of NixAdmin. High Five Nix!! 😉

On the other hand, we can use inbuilt tool like rysnc command for taking backups. rsync command is often used to take incremental backup of the data. Generally, one will be taking backup of data to remote host via rsync with the use of SSH keys. Thus synchronization can be scripted effortlessly and without human intervention. But what if rsync cannot be performed due to failed SSH connection ? Obviously our backup task will fail. Would it be nice if we can test the SSH connection to the remote host first before performing the synchronization of data? ie setting up a Bash Script to test SSH connection for rsync. If test fails, its a problem and Admin should notice it. If it passes, its all good and our backup task will run as expected. Right ? 🙂

We can test the SSH connectivity using simple bash script. Of course there are many ways and best approaches to manage this scenario. Lets do it in simple way ?.. Hmm.. I guess this is so somehow a simple approach.

Here we assume that we have setup SSH key based access for Password-less authentication. We can use the following bash script in such case to test the SSH connection to our Remote Server ( lets say our Backup Server ).

#!/bin/bash
BACKUP_HOST=10.5.10.22 #IP Of the remote Server
ssh $BACKUP_HOST “echo 2>&1″
exstat=$?

if [ $exstat -eq 0 ] then
{
echo ” SSH OK ”
}
else
{
echo ” SSH DOWN ”
}
fi

Pheww….That was pretty straight forward. Now we can include our rsync command in the loop. So a SSH test will be done at first before the rsync stuff.

Lets modify the script like as follows.

#!/bin/bash
BACKUP_HOST=10.5.10.22
ssh $BACKUP_HOST “echo 2>&1″
exstat=$?

if [ $exstat -eq 0 ] then
{
rsync -avz /data $BACKUP_HOST:/backup       #your rsync command here
echo ” Rsync Done !” | mail -s ‘Backup Completed’ mail@admin
}
else
{
echo ” Failed SSH – Rsync Not Done !” | mail -s ‘Backup Failed’ mail@admin
}
fi

In this way we can test SSH connection before performing the backup task using rsync.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *