一:定時備份數據庫 backup.sh 內容:java
(我寫的第一個腳本(本人是開發,腳本內容不夠優雅,主要學習總結)mysql
1)指定HOST備份腳本backup.sh ,數據庫和備份能夠不在同臺機器sql
#!/bin/sh echo "<== [author:DY] MySQL備份腳本啓動中...請勿中斷!" source /etc/profile HOST="172.xx.xx.xx" PWD="xxxxxx" BACKUP_PATH="/opt/backup-auto/" if [ ! -d "$BACKUP_PATH" ];then mkdir "$BACKUP_PATH" fi ARRAY_DB=$(mysql -u root -h ${HOST} -p${PWD} -e "SHOW DATABASES"|awk 'NR>1') #echo "即將備份的數據庫包含:$ARRAY_DB" for db in ${ARRAY_DB[@]} do if [ ! -d "$BACKUP_PATH${db}" ];then mkdir "$BACKUP_PATH${db}" fi if [ "information_schema" = ${db} ];then echo "跳過${db}" else /usr/local/mydumper-0.9.1/mydumper -u root -p $PWD -h $HOST -B ${db} -c -o $BACKUP_PATH${db}/`date +%Y%m%d%H%M%S` echo "[${db}] 備份完成" fi done echo "<==[author:DY] $HOST MySQL 備份完成 ==>"
二:每隔30分鐘分鐘執行一次 數據庫
(注意這裏是邏輯備份,生產環境建議選擇天天夜間備份一次) 這裏是全量備份學習
#crontab -e 中設置執行策略和執行腳本
*/30 * * * * /bin/sh /opt/backup.shrest
#service crond restart 重啓定時任務服務code
三:恢復數據庫腳本reback.shorm
#./reback.sh all //恢復全部數據庫crontab
#./reback.sh [數據庫名] //恢復指定數據庫開發
1)恢復到指定機器上 reback.sh
#!/bin/sh echo "<== [author:DY] MySQL備份恢復中...請勿中斷!(默認從最新的一次備份中恢復)" source /etc/profile HOST="172.30.xx.xx" PWD="DYxxxxx" BACKUP_PATH="/opt/backup-auto/" DB_ARRAY=`ls $BACKUP_PATH` if echo "${DB_ARRAY[@]}" | grep -w "$1" &>/dev/null; then echo ""; elif [ "all" = $1 ]; then echo ""; else echo $"Ukonwn command: $1 ; it shoud be a db name" exit 1 fi for dir in ${DB_ARRAY} do NEW_BACKUP_PATH=`cd $BACKUP_PATH${dir} && ls | tail -1` case "$1" in "${dir}") /usr/local/mydumper-0.9.1/myloader -u root -p $PWD -h $HOST -B ${dir} -o -d $BACKUP_PATH${dir}/$NEW_BACKUP_PATH echo "${dir} 數據庫還原成功" ;; "all") if [ "mysql" = ${dir} -o "sys" = ${dir} -o "performance_schema" = ${dir} -o "information_schema" = ${dir} ];then echo "跳過 ${dir}" else /usr/local/mydumper-0.9.1/myloader -u root -p $PWD -h $HOST -B ${dir} -o -d $BACKUP_PATH${dir}/$NEW_BACKUP_PATH echo "${dir}用戶數據庫還原成功" fi ;; esac done echo "<== [author:DY] $HOST MySQL ${1} 數據表恢復完成 ==>"