Bash Script – Sync a File to an Array of Hosts

#!/bin/bash
# Sync a file to a remote set of servers using scp and check using diff
# NOTE: This requires the use of 'sshpass' and IS insecure in nature
# It also assumes the user credentials are identical on all hosts
# and that they have the necessary permissions on the remote directory
# Author: Nathan Thomas
LOGFILE='/var/log/sync_files.log'
SSH_USER='non-root-user'
SSH_PASS='password'
CONF_FILE='/etc/appdir/myconfig.conf'
SERVERS=('server1.fqdn.com' 'server2.fqdn.com' 'server3.fqdn.com')
for HOST in "${SERVERS[@]}" ; do
        # NOTE: This won't work if the host keys are not already in the ssh cache
        # Flush ssh hosts - Either uncomment these two lines on first run or you could leave it uncommented for hosts that change addresses a lot

        #ssh-keygen -R ${HOST}
        #ssh-keyscan -H ${HOST} >> ~/.ssh/known_hosts
        if [ -f "${CONF_FILE}" ] ; then
                sshpass -p "${SSH_PASS}" scp ${CONF_FILE} ${SSH_USER}@${HOST}:${CONF_FILE}
                if [ "$?" -eq "0" ] ; then  # On success, check file for differences
                        RESULT=`sshpass -p "${SSH_PASS}" ssh ${SSH_USER}@${HOST} "cat ${CONF_FILE}" | diff -q - ${CONF_FILE} | grep "differ" | wc -l`
                        unset -v ERROR
                        for ERROR in "${PIPESTATUS[@]}" ; do
                                if [ "${ERROR}" != "0" ] ; then
                                        echo "`date "+%Y %a %b%e %T"` - Pipe Error: ${ERROR}." >> ${LOGFILE}
                                fi
                        done
                        if [ "${RESULT}" -eq "0" ] ; then  # The files match
                                echo "`date "+%Y %a %b%e %T"` - Config file is in sync on ${HOST}." >> ${LOGFILE}
                        elif [ "${RESULT}" -eq "1" ] ; then  # Files contain differences somehow
                                echo "`date "+%Y %a %b%e %T"` - For some reason the files did not sync properly on ${HOST}." >> ${LOGFILE}
                        else
                                echo "`date "+%Y %a %b%e %T"` - An unexpected error occurred while checking the files for differences on ${HOST}." >> ${LOGFILE}
                        fi
                else
                        echo "`date "+%Y %a %b%e %T"` - An error occurred while copying the file to ${HOST}". >> ${LOGFILE}
                fi
        else
                echo "`date "+%Y %a %b%e %T"` - The file ${CONF_FILE} does not exist...exiting." >> ${LOGFILE}
                break
        fi
done

One Reply to “Bash Script – Sync a File to an Array of Hosts”

  1. In actuality, it’s probably just as easy to say screw all that and generate a password-less RSA SSH key and import it on your other server and set permissions on the config files.

Leave a Reply