一、創建備份用戶
[(none)]> create user 'buser'@'localhost' identified by 'tmrQ';[(none)]> GRANT RELOAD, PROCESS, LOCK TABLES, REPLICATION CLIENT ON *.* TO 'buser'@'localhost';[(none)]> flush privileges;
二、腳本
# cat mysql_bask.sh
#!/bin/bash
# MariaDB 10.3.35 Backup Script
# 支持全量備份 + 增量備份 + 自動清理
# 使用前請配置以下變量# ===== 配置區域 =====
MYSQL_USER="buser" # 備份專用數據庫賬號
MYSQL_PASSWORD="tmrQ" # 備份賬號密碼
BACKUP_DIR="/opt/mysql_backup" # 備份存儲目錄
FULL_BACKUP_INTERVAL=7 # 全量備份間隔(天)
RETENTION_DAYS=30 # 備份保留天數
LOG_FILE="/var/log/mariadb_backup.log" # 日志文件路徑
# ===================# 創建必要目錄
mkdir -p ${BACKUP_DIR}/{full,incr} &> /dev/null# 日志記錄函數
log() {echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" | tee -a $LOG_FILE
}# 數據庫連接檢查
check_db_connection() {if ! mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD} -e "SHOW STATUS;" &> /dev/null; thenlog "錯誤:無法連接到MariaDB服務器!"exit 1fi
}# 全量備份函數
full_backup() {local backup_name="full-$(date +%Y%m%d_%H%M%S)"local target_dir="${BACKUP_DIR}/full/${backup_name}"log "開始全量備份: ${backup_name}"mariabackup --backup \--user=${MYSQL_USER} \--password=${MYSQL_PASSWORD} \--target-dir=${target_dir} 2>> $LOG_FILEif [ $? -eq 0 ]; thenlog "全量備份成功: ${backup_name}"echo "${target_dir}" > ${BACKUP_DIR}/last_full_backupelselog "全量備份失敗!"rm -rf ${target_dir}exit 1fi
}# 增量備份函數
incremental_backup() {local base_dir=$(cat ${BACKUP_DIR}/last_full_backup)if [ -z "$base_dir" ]; thenlog "未找到基準備份,執行全量備份..."full_backupreturnfilocal backup_name="incr-$(date +%Y%m%d_%H%M%S)"local target_dir="${BACKUP_DIR}/incr/${backup_name}"log "開始增量備份: ${backup_name}"log "基準備份: $(basename ${base_dir})"mariabackup --backup \--user=${MYSQL_USER} \--password=${MYSQL_PASSWORD} \--target-dir=${target_dir} \--incremental-basedir=${base_dir} 2>> $LOG_FILEif [ $? -eq 0 ]; thenlog "增量備份成功: ${backup_name}"elselog "增量備份失敗!"rm -rf ${target_dir}exit 1fi
}# 清理舊備份
clean_old_backups() {log "清理超過${RETENTION_DAYS}天的備份..."find ${BACKUP_DIR}/full -type d -mtime +${RETENTION_DAYS} -exec rm -rf {} +find ${BACKUP_DIR}/incr -type d -mtime +${RETENTION_DAYS} -exec rm -rf {} +
}# 主執行邏輯
main() {log "===== 備份開始 ====="check_db_connection# 檢查是否需要全量備份if [ ! -f "${BACKUP_DIR}/last_full_backup" ] || \[ $(find "${BACKUP_DIR}/last_full_backup" -mtime +${FULL_BACKUP_INTERVAL}) ]; thenfull_backupelseincremental_backupficlean_old_backupslog "===== 備份完成 ====="
}# 執行主函數
main
三、添加執行權限
# chmode +x mysql_bask.sh
四、配置任務計劃
# crontab -l
0 4 * * * /usr/bin/sh /opt/scripts/mysql_bask.sh
五、恢復步驟
5.1 全量備份恢復
mariabackup --copy-back --target-dir=/backup/mariadb/full/full-YYYYMMDD_HHMMSS
5.2 增量備份恢復
# 先恢復全量備份
mariabackup --copy-back --target-dir=/backup/mariadb/full/base_backup# 再應用增量備份
mariabackup --copy-back --target-dir=/backup/mariadb/full/base_backup \--incremental-dir=/backup/mariadb/incr/incr_backup_dir
六、腳本說明
備份類型:
全量備份:每?
FULL_BACKUP_INTERVAL
?天執行一次增量備份:基于上次全量備份進行增量備份
自動清理:
自動刪除超過?
RETENTION_DAYS
?天的舊備份
日志記錄:
詳細記錄備份過程到日志文件
控制臺和文件雙重輸出
安全機制:
數據庫連接檢查
備份失敗自動清理殘留文件
錯誤退出機制
?七、配置腳本
修改腳本頂部的配置參數(用戶名、密碼、目錄等)
設置合適的備份保留策略
八、首次備份后的目錄結構
?