(Linux环境)MySQL数据库定时备份

(Linux环境)MySQL数据库定时备份_第1张图片
最近遇到MySQL数据库备份的问题,其实备份可以直接备份数据库数据目录,但是这个方法比较困难,得停数据库才能备份。于是写了shell脚本,采用for循环备份MySQL里面的所有库,然后用rsync软件将备份数据同步到其他服务器上实现异地备份,保留7天的备份数据。脚本展示如下:

#!/bin/bash
#date 2020-04-21
#author by believer 
#discription: This script use to backup mysql data and send to remote server:192.168.1.100 dir:/data/databackup.
#rollback data:mysql -uroot -proot databasename < back.sql
#设置环境变量
source /etc/profile > /dev/null 2>&1
BACKUP_TIME=`date "+%Y%m%d%H%M%S"`
BACKUP_DIR='/opt/databack/backupdata'
BACKUP_LOG='/opt/databack/log'
ROOT_PASSWORD='123456'
REMOTE_USER='test'
REMOTE_DIR='/data/databackup'
REMOTE_IP='192.168.1.100'
export MYSQL_PWD="$ROOT_PASSWORD"
#开始备份所有数据库
for database in buse supershow goods 
do
 echo "mysqldump -uroot -h127.0.0.1  $database > ${BACKUP_DIR}/${database}_${BACKUP_TIME}_bak.sql" >> ${BACKUP_LOG}/${database}_${BACKUP_TIME}_dump.log
 mysqldump -uroot -h127.0.0.1  $database > ${BACKUP_DIR}/${database}_${BACKUP_TIME}_bak.sql 2>> ${BACKUP_LOG}/${database}_${BACKUP_TIME}_dump.log
 if [ $? -eq '0' ];
 then
    echo "backup $database successful !" >> ${BACKUP_LOG}/${database}_${BACKUP_TIME}_dump.log
 else
    echo "backup $database fail !!!" >> ${BACKUP_LOG}/${database}_${BACKUP_TIME}_dump.log
 fi
done
#打包SQL文件成tar.gz文件并且同步到异地机器
cd ${BACKUP_DIR}/
tar -zcvf mysql_${BACKUP_TIME}.tar.gz *.sql 
sleep 3s
rm -f *.sql 
sleep 5s
#rsync -avzP --delete 该命令发现远端服务器与本机文件不一致,会删除远端服务器不一样的文件,故尽量同步远程的普通用户。root权限比较大,存在风险,生产环境必须谨慎!!! 
rsync -avzP --delete ${BACKUP_DIR}/ ${REMOTE_USER}@${REMOTE_IP}:${REMOTE_DIR}/
#保留7天内的备份文件
cd ${BACKUP_DIR}/
find ${BACKUP_DIR}/ -type f -mtime +7 -exec rm -f {} \;
#保留7天内的日志
cd ${BACKUP_LOG}/
find ${BACKUP_LOG}/ -type f -mtime +7 -exec rm -f {} \;

欢迎各路大佬转载交流~~

你可能感兴趣的:(数据库,linux,运维,mysql)