• 搜索
  • 夜间模式
    ©2026  依刻学习 Theme by OneBlog

    依刻学习博客

    搜索
    标签
  • 首页>
  • 学习的一天>
  • 正文
  • 使用xtrabackup实现mysql自动备份

    2025年09月04日 61 阅读 0 评论 4508 字

    前言

    前两天看见网上有人抱怨mysql备份有点麻烦,所以我这两天写了个自动化备份mysql的脚本

    脚本

    #!/usr/bin/bash
    
    StepShow () {
      #tipEcho 第几步  主题
      echo -e "\n------------------------------------------"
      echo -e "\033[34;3mstep $1 :  $2\033[0m"
      echo -e "------------------------------------------\n"
    }
    
    WarnShow () {
      echo -e "\n\033[33;3m Warn: $1   \033[0m"
    }
    
    ErrorShow () {
      echo -e "\n\033[31;43;4m ERROR: $1     \033[0m"
    }
    
    TipShow () {
      echo -e "\n\033[32;3m TIP: $1     \033[0m"
    }
    
    
    TestMysqlRunnung () {
      systemctl start mysqld &> /dev/null
      # 测试mysql是否运行
      if [ $( ps -aux|grep 'mysqld '|wc -l) -gt 1 ]; then
        # 进一步检查
        mysql -u backup -p"${password}" -e "SELECT 1" &>/dev/null
        if [ $? -eq 0 ];then
          echo 'mysql正在运行'
        else
          echo -e '\033[31m mysql没有运行 \033[0m'
        fi
      else
        echo -e '\033[31m mysql没有运行 \033[0m'
      fi
    }
    
    TestXtrabackupExist () {
      # 测试是否安装Xtrabackup
      xtrabackup --version &>/dev/null
      if [ $? -eq 0 ]; then
        echo 'xtrabackup已安装'    
      else
          echo 'xtrabackup未安装' 
          exit 2
      fi
    }
    
    
    CheckBackupDir () {
      # 创建备份目录
      echo '注意会清除目录内同名文件'
      if [ ! -d "${backupDir}" ];then
        rm ${backupDir} -f
        mkdir ${backupDir}
      fi
    }
    
    ChooseStrategy(){
      # 创建策略文件用于永久存储策略
      if [ $(ls ${backupDir}|grep strategy|wc -l) -ne 1 ];then
        touch ${backupDir}/strategy
      fi
      # 在strategy为空时才进行策略选择,否则会直接读取
      while [ $(cat ${backupDir}/strategy|wc -l) -eq 0 ];do
        echo -e "1.增量备份\n2.差异备份"
        read -p '选择:'  choose
        if [ ${choose} -eq 1 ];then
          echo -e 'increment\n###' >  ${backupDir}/strategy
        elif [ ${choose} -eq 2 ];then
          echo -e 'difference\n###' >  ${backupDir}/strategy
        else 
            echo '错误输入,重新输入'
        fi
      done
      echo '创建成功'
    }
    
    CheckLatest(){
      latestBackup=$(cat ${backupDir}/strategy|tail -1)
      if [ ${latestBackup} == '###' ];then
        status=1     # 需要全量备份,status为1
        echo '没有备份,即将完整备份'
      else  # 已经全量备份就要进行差异或增量备份
        strategy=$(cat ${backupDir}/strategy|head -1)
        [ ${strategy} == 'difference' ] && status=2   # 差异备份
        [ ${strategy} == 'increment' ] && status=3    # 增量备份
        echo "最新的备份为${latestBackup}"
      fi
    }
    
    
    Backup() {
      oldtarget=${latestBackup}
      # oldtarget--inc3  newtarget--inc4
      # 初始化newtarget
      if [ ${oldtarget} == '###' ];then
        newtarget='base'
      elif [ ${oldtarget} == 'base' ];then
        newtarget="$(cat ${backupDir}/strategy|head -1|cut -c1-3)1"
      else
        newtarget="$(echo ${oldtarget}|cut -c1-3)$(($(echo ${oldtarget}|cut -c4)+1))"
      fi
      echo "${oldtarget}-----${newtarget}"
    
      if [ ${status} -eq 1 ];then    # 没有完整备份
        xtrabackup  --backup  --user=${user}  --password="${password}"  --target-dir=${backupDir}/${newtarget}  &>> ${backupDir}/log
      elif [ ${status} -eq 2 ]; then        # 需要差异备份 
        oldtarget='base'    # 差异备份的 oldtarget固定
        xtrabackup  --backup  --user=${user}  --password="${password}"  --target-dir=${backupDir}/${newtarget}  --incremental-basedir=${backupDir}/${oldtarget} &>> ${backupDir}/log
      elif [ ${status} -eq 3 ]; then        # 需要增量备份 
        xtrabackup  --backup  --user=${user}  --password="${password}"  --target-dir=${backupDir}/${newtarget}  --incremental-basedir=${backupDir}/${oldtarget} &>> ${backupDir}/log
      else
        echo -e "错误的状态:${status}"
        exit 1
      fi
      [ $? -eq 0 ] && TipShow "备份成功" || ErrorShow "备份失败" 
      echo ${newtarget} >> ${backupDir}/strategy
    }
    
    
    main() {
      declare -A strategytofile
      status=0 # 状态,0待定,1为需要完整备份,2为需要差异备份,3为需要增量备份
      strategytofile['increment']='inc'
      strategytofile['difference']='dif'
      read -p '请输入用户:'  password
      user=${1:-'backup'}
      read -p '请输入密码:'  password
      password=${password:-'StrongPass!123'}
      read -p '请输入目录:'  backupDir
      backupDir=${1:-'/backup/mysql'}
      backupDir=${backupDir%/}
      # 此方法有bug,不是按顺序的,使用固定的文件内容替代不可控的排序
      # latestBackup=$(find ${backupDir} -maxdepth 1  -type d |tail -1|xargs basename)
      StepShow 1 '测试mysql'
      TestMysqlRunnung
      StepShow 2 '测试Xtrabackup'
      TestXtrabackupExist
      StepShow 3 '检查备份目录是否存在'
      CheckBackupDir
      StepShow 4 '检查备份策略'
      ChooseStrategy
      StepShow 5 '检查最新的备份'
      CheckLatest
      StepShow 6 '备份'
      Backup
    
    }
    
    
    main 
    
    
    
    ###########################
    # README
    # 该脚本用于自动化的完成mysql的增量/差异备份
    # - 具有一定的报错检查机制
    # - 完善的日志内容
    # - 一次配置,永久记住
    
    ###########################
    # 2025.9.2   70%,在没有base情况下没有正常进行完整备份
    # 2025.9.3   完成,正常运行,自动备份
    
    ###########################
    # 升级方向
    # 1.自解压安装xtrabackup
    # 2.提供更高程度的自定义配置
    # 3.压缩/加密备份
    # 4.与自动恢复的联动
    本文著作权归作者 [ wymm ] 享有,未经作者书面授权,禁止转载,封面图片来源于 [ 互联网 ] ,本文仅供个人学习、研究和欣赏使用。如有异议,请联系博主及时处理。
    取消回复

    发表留言
    回复

    Copyright©2026  All Rights Reserved.  Load:0.039 s
    Theme by OneBlog V3.6.5
    夜间模式

    开源不易,请尊重作者版权,保留基本的版权信息。