MySQL完全备份脚本:数据+二进制日志+备份日志

时间:2024-06-10 09:08:08

一. 脚本须知

  1.mysql数据文件和二进制日志文件最好保存在不同的分区或存储设备上

  2.备份完成后注意修改数据的权限以防止泄露重要信息,哪些主机哪些用户可以用来恢复

  3. 查看导出的2进制日志文件看是否符合逻辑和业务,2进制日志文件只能保证物理上数据即时点还原,却保证不了数据逻辑上正确恢复(比如drop语句)

  4.为了保证数据恢复没有问题建议在测试机上做一次数据恢复测试

  5.恢复测试OK可以放到crontab定时任务中

 #!/bin/bash
#
# Function:实现mysql完全备份
# Notes: # 定义备份使用到的相关变量(需要根据用户实际环境做相应的修改)
backup_data=/backup/mysql/full
backup_binlog=/backup/mysql/logbin
mysql_binlog=/mydata/log-bin
mysql_bin_path=`ps -ef | grep -E "mysqld[[:space:]]+" | awk -F ' ' '{ print $8 }' | sed -r 's@[^/]+/?$@@'`
mysql_user=root
mysql_password=mysqldba
logfile=/var/log/mysqldump.log # 函数定义 ########################[MySQL健康检测]######################
health_check() {
if pgrep mysqld &> /dev/null;then
mysqld_pid=`pgrep -l mysqld | grep -E "mysqld\>" | awk '{ print $1 }'`
echo "$(date +"%Y-%m-%d %H:%M:%S") $mysqld_pid [Note] Server Mysql is Running ..." >> $logfile
else
service mysqld start &> /dev/null || echo "$(date +"%Y-%m-%d %H:%M:%S") [Warning] Server MySQL is not running, backup failed" >> $logfile && return 5
fi
} #######################[mysqldump完全备份]###################
full_backup(){
local backup_name=full-`date +%F-%T`.sql
[ ! -d $backup_data ] && mkdir -p $backup_data
${mysql_bin_path}mysqldump -u$mysql_user -p$mysql_password --all-databases --lock-all-tables --flush-logs --master-data=2 \
--triggers --routines --events --set-gtid-purged=off -r ${backup_data}/$backup_name &> /dev/null
if grep -q "CHANGE MASTER TO" ${backup_data}/$backup_name ;then
return 0
else
return 5
fi
} ########################[Mysql 二进制日志备份]#####################
bin_backup(){
[ ! -d $backup_binlog ] && mkdir -p $backup_binlog
cd $mysql_binlog
tar -jcf bin-`date +"%F-%H'%M'%S"`.tar.bz2 * &> /dev/null
\mv -f bin*.tar.bz2 $backup_binlog
} # 主函数main health_check
if [ $? -eq 0 ];then
echo "$(date +"%Y-%m-%d %H:%M:%S") [Note] MySQL full backup start ..." >> $logfile
else
echo "$(date +"%Y-%m-%d %H:%M:%S") [Warning] Server MySQL is not running, backup failed" | mail -s "mysql backup is failed" root@`hostname`
fi
full_backup
if [ $? -eq 0 ];then
echo "$(date +"%Y-%m-%d %H:%M:%S") [Note] MySQL full backup is finished" >> $logfile
chmod -R 600 $backup_data
else
echo "$(date +"%Y-%m-%d %H:%M:%S") [Warning] Function full_backup() execution failed, backup was interrupted" | cat | tee -a $logfile | mail -s "mysql backup is failed" root@`hostname`
fi
echo "$(date +"%Y-%m-%d %H:%M:%S") [Note] MySQL binary log file backup is started ..." >> $logfile
bin_backup
if [ $? -eq 0 ];then
echo "$(date +"%Y-%m-%d %H:%M:%S") [Note] MySQL binary log file backup is finished " >> $logfile
chmod -R 600 $backup_binlog
else
echo "$(date +"%Y-%m-%d %H:%M:%S") [Warning] Mysql binary log file backup is not completed" | cat | tee -a $logfile | mail -s "mysql binary log backup failed" root@`hostname`
fi

二.实例效果图

脚本执行完查看备份数据和日志

 MySQL完全备份脚本:数据+二进制日志+备份日志

脚本执行过程跟踪

MySQL完全备份脚本:数据+二进制日志+备份日志

MySQL完全备份脚本:数据+二进制日志+备份日志

加入crontab任务

 MySQL完全备份脚本:数据+二进制日志+备份日志