#!/bin/bash ################################################################################ # backup_remote.sh # create @17.04.17 ################################################################################ . /path/to/utils.sh ## # settings # LIST_DIR='/path/to/backup.d' LIST_EXT='.list' DEST_DIR='/path/to/dest' LOG_DIR='/var/log/rsync' SSH_USER='collector' SSH_PRIVKEY='/path/to/id_ed25519' RSYNC_CMD='/usr/bin/rsync' RSYNC_DEFOPTS='--delete --exclude lost+found' ## # check variables. # if [ ! -f "${RSYNC_CMD}" ] || [ ! -x "${RSYNC_CMD}" ]; then error "'${RSYNC_CMD} is not executable." exit 1 fi if [ ! -d "${LIST_DIR}" ] || [ ! -x "${LIST_DIR}" ]; then error "Cannot access to '${LIST_DIR}'." exit 1 fi if [ ! -f "${SSH_PRIVKEY}" ] || [ ! -r "${SSH_PRIVKEY}" ]; then error "Cannot access to '${SSH_PRIVKEY}'." exit 1 fi if [ ! -d "${DEST_DIR}" ] || [ ! -w ${DEST_DIR} ]; then error "Cannot access to '${DEST_DIR}'." exit 1 fi if [ ! -d "${LOG_DIR}" ] || [ ! -w ${LOG_DIR} ]; then error "Cannot access to '${LOG_DIR}'." exit 1 fi ## # check argument # if [ -z "$1" ]; then error "usage: ${0} " exit 1 fi HOST=${1} if [ "${HOST}" = 'local' ]; then error "Not acceptable hostname '${HOST}'." exit 1 fi FILE="${LIST_DIR}/${HOST}${LIST_EXT}" if [ ! -f "${FILE}" ] && [ ! -r "${FILE}" ]; then error "Cannot access to '${FILE}'." exit 1 fi ## # start main. # LOG_FILE="${LOG_DIR}/${HOST}.$(date +%Y-%m-%d-%H.%M.%S).log" RET=0 info "Backup start." info "Rsync log is ${LOG_FILE}" while read DIR OPTS; do # skip blank line. if [[ "${DIR}" =~ ^\s*$ ]]; then continue fi # skip comment line. if [[ "${DIR}" =~ ^\s*# ]]; then continue fi if [[ "${DIR}" =~ [^/]$ ]]; then warn "Directory path should ends with '/'." DIR="${DIR}/" fi SRC="${HOST}:${DIR}" DST="${DEST_DIR}/${HOST}${DIR}" # create directory tree /bin/mkdir -p ${DST} if [ $? -ne 0 ]; then error "Cannot create directory: '${DST}'." RET=2 continue fi info "Start sync from '${SRC}' to '${DST}'." ${RSYNC_CMD} -avvr \ --rsh "ssh -l ${SSH_USER} -i ${SSH_PRIVKEY} -o strictHostKeyChecking=no" \ --rsync-path="sudo rsync" \ ${RSYNC_DEFOPTS} ${OPTS} \ ${SRC} ${DST} \ >> ${LOG_FILE} 2>&1 if [ $? -ne 0 ]; then error "Failed to rsync from '${SRC}' to '${DST}': $!" RET=3 else info "Succeeded to rsync from '${SRC}' to '${DST}'." fi done < ${FILE} info "Backup finished." exit ${RET}