一个简单的批量备份日志脚本

接上文。上文免密登录后,这篇文章简单做个日志定期备份,将其他机器上的日志整合到本地。逻辑较为简单,可以按需修改。最终效果是,每天将若干机器的文件整理成一个压缩包保存到本地,同时删除一年前的备份。这里就不过多赘述了。

#!/bin/bash

#应用名
APPNAME="KOMACHI"
#远程主机列表
TARGET_IPS="app1:auth|ticket,app2:auth|base,app3:ticket|manager,app4:manager|base"
#远程主机文件目录
TARGET_FOLDER="/var/local/logs"
#远程主机用户及密码
TARGET_USER_NAME="kelu"
#备份几天前的日志文件
DAYS_AGO=1
#本地备份目录
LOCAL_FOLDER="/backup/logs"
#循环备份文件
backupdate=`date -d "${DAYS_AGO} day ago" +%Y-%m-%d`
deletedate=`date -d "1 year ago" +%Y-%m-%d`

backup_file(){
	localFolder=$1
  remoteIp=$2
  remoteBackupFolder=$3
	errorIgnore=$4

	if [ ! -d ${localFolder} ] ; then
		mkdir -p ${localFolder}
	fi

  if [ $errorIgnore ]; then
		scp -r ${remoteIp}:${remoteBackupFolder} ${localFolder} > /dev/null 2>&1
    return 0
	else
		scp -r ${remoteIp}:${remoteBackupFolder} ${localFolder} 1>/dev/null
	fi
}

run_backup(){
	echo ">>>>>>>>>>>>>> $backupdate 开始备份..."
        errorFlag=0
	IFS=","
	arrayIP=($TARGET_IPS)
	for ipInfo in ${arrayIP[@]}
	do
		echo ">>>>>>>>>>>>>> ${ipInfo}"
		IFS=":"
		arrayIPInfo=($ipInfo)
		remoteIp=${arrayIPInfo[0]}
		subInfo=${arrayIPInfo[1]}
#		echo -e "主机IP:\t\t${remoteIp}"
#		echo -e "主机备份目录:\t${subInfo}"

		IFS="|"
		arrayProgram=($subInfo)
		for program in ${arrayProgram[@]}
		do
			localFolder=${LOCAL_FOLDER}/${APPNAME}-${backupdate}/${remoteIp}/${program}
      remoteFolder=$TARGET_FOLDER/${program}/${backupdate}/*
			localBatchFolder=${LOCAL_FOLDER}/${APPNAME}-${backupdate}/${remoteIp}/batch/${program}
			remoteBatchFolder=$TARGET_FOLDER/batch/${program}/${backupdate}/*
      backup_file $localFolder $remoteIp $remoteFolder
			if [ $? -ne 0 ]; then
				errorFlag=1
			fi

      backup_file $localBatchFolder $remoteIp $remoteBatchFolder "ignore"
			if [ $? -ne 0 ]; then
				errorFlag=1
			fi
		done

	done

  if [ $errorFlag -ne 0 ]; then
		echo ">>>>>>>>>>>>>> $backupdate 备份结束,部分异常,请确认!"
	else
		echo ">>>>>>>>>>>>>> $backupdate 备份完成。"
  fi

  cd ${LOCAL_FOLDER}
	tar czvf ${APPNAME}-${backupdate}.tgz ${APPNAME}-${backupdate} 1>/dev/null
  rm -r ${APPNAME}-${backupdate}
  rm -rf ${APPNAME}-${deletedate}.tgz
}

run_backup


一个 ssh 设置免密登陆脚本 FreeBuf 的一些事 - freebuf.com