MySQL指定数据库全量备份表结构和数据,将备份文件发送到其他服务器
#!/bin/bash
mysqldump=/usr/bin/mysqldump
BACKUP_FOLDERNAME="/usr/local/mysql/backup_all"
DB_HOSTNAME="xx.xx.xx.xx"
DB_USERNAME="root"
DB_PASSWORD="password"
DATABASES=(
"saas_partition_xxx1"
"saas_partition_xxx2"
)
echo "数据库备份工具"
CURRENT_DATE=$(date +%F)
BACKUP_FOLDER="${BACKUP_FOLDERNAME}/${CURRENT_DATE}"
mkdir $BACKUP_FOLDER
count=0
while [ "x${DATABASES[count]}" != "x" ];do
count=$(( count + 1 ))
done
echo "[+] 【${count}】个数据库开始备份..."
for DATABASE in ${DATABASES[@]};do
echo "[+] Mysql-Dumping: ${DATABASE}"
echo -n " Began: ";echo $(date)
if [ ! -d "${BACKUP_FOLDER}" ];then
mkdir ${BACKUP_FOLDER}
fi
if $($mysqldump --quick --events --flush-logs --single-transaction -h ${DB_HOSTNAME} -u${DB_USERNAME} -p${DB_PASSWORD} ${DATABASE} > "${BACKUP_FOLDER}/${DATABASE}.sql"); then
echo " 【$DATABASE】备份完成!"
else
echo " 【$DATABASE】备份失败!"
fi
echo -n " 所有数据库备份完成: ";echo $(date)
done
echo
echo "开始压缩备份文件【${BACKUP_FOLDER}/*.sql】到【${BACKUP_FOLDER}/dbback_${CURRENT_DATE}.tar.gz】"
cd ${BACKUP_FOLDER}
tar czf ${BACKUP_FOLDER}/dbback_${CURRENT_DATE}.tar.gz *.sql
rm -f ${BACKUP_FOLDER}/*.sql
echo "完成压缩备份文件"
echo "开始传输文件到其他服务器"
/usr/bin/expect <<-EOF
#!/usr/bin/expect -f
set timeout 20
spawn scp ${BACKUP_FOLDER}/dbback_${CURRENT_DATE}.tar.gz root@xx.xx.xx.xx:/opt/project/dbback
expect "root@xx.xx.xx.xx's password:"
exec sleep 1
send "password\n"
expect eof;
EOF
echo "完成传输文件到其他服务器"
echo "删除 10 天前的备份文件"
d=`date -d '10 days ago' '+%Y-%m-%d'`
cd ${BACKUP_FOLDER}/..
if [ "`pwd`" != "/" ];then
rm -rf dbback_${d}.tar.gz
fi
echo "清理10天前的备份文件完成"
echo "所有全量备份工作完成"