MySQL备份脚本

一、MySQL备份脚本

#!/bin/bash  
# script_name: db_backup.sh  
# author: Michael Ho
# contact: herui1991@sina.cn
# 172.50.1.119 为专门的备份服务器,需要做一下服务器之间免密码登录

# 备份的数据库名
DOCKER_NAME=zzmysql
DATABASES=(
    "managesystem"                    
)
USER="root"
PASSWORD="ZZ2018info"
BACKUP_DIR=/data/backup
LOGFILE=/data/backup/data_backup.log 
DATE=`date +%Y%m%d_%H%M`

cd $BACKUP_DIR
# 开始备份之前,将备份信息头写入日记文件   
echo "--------------------" >> $LOGFILE   
echo "BACKUP DATE:" $(date +"%y-%m-%d %H:%M:%S") >> $LOGFILE   
echo "-------------------" >> $LOGFILE

for DATABASE in ${DATABASES};do
    # 物理机版
    # /usr/local/mysql/bin/mysqldump -u$USER -p$PASSWORD --events -R --opt $DATABASE | gzip > ${BACKUP_DIR}\/${DATABASE}_${DATE}.sql.gz
    
    # docker版
    /usr/local/bin/docker exec $DOCKER_NAME mysqldump -u$USER -p$PASSWORD --events -R --opt $DATABASE | gzip > ${BACKUP_DIR}\/${DATABASE}_${DATE}.sql.gz
    if [ $? == 0 ];then
        echo "$DATE--$DATABASE is backup succeed" >> $LOGFILE
    else
        echo "Database Backup Fail!" >> $LOGFILE
        curl -H "Content-type: application/json" -X POST -d '{"msgtype": "text","text": {"content": "'$DATABASE'备份失败"}}' https://oapi.dingtalk.com/robot/send?access_token=xxx        
    fi
done

# 判断数据库备份是否全部成功,全部成功就同步到异地备份服务器
if [ $? == 0 ];then
    /usr/bin/rsync -zrtopg --delete /data/backup/* root@172.50.1.119:/home/data/mysql/backup/ > /dev/null 2>&1
else
    echo "Database Backup Fail!" >> $LOGFILE   
    # 备份失败后向钉钉发出告警
    curl -H "Content-type: application/json" -X POST -d '{"msgtype": "text","text": {"content": "同步到172.50.1.119失败"}}' https://oapi.dingtalk.com/robot/send?access_token=xxx
fi

# 删除30天以上的备份文件  
find $BACKUP_DIR  -type f -mtime +30 -name "*.gz" -exec rm -f {} \;
exit 0

二、注意事项

1.docker 、mysqldump一定要是绝对路径,否则加入到crontab是执行失败的,执行出来的文件是空的

2.access_token=xxxxxxxxxxxxxxxxxxxx   这个值是自己钉钉申请的token值

 
posted @ 2020-02-28 12:41  何瑞  阅读(249)  评论(0编辑  收藏  举报