简介

在这个数据为王的时代,数据的备份十分重要,这里就分享一篇mysql数据库自动备份的脚本(是从网上搜到的),其将配置文件和备份脚本分离,提高了安全性,脚本风格规范严谨,分享给大家希望对需要的小伙伴有所帮助。

mysql备份配置文件

配置文件中,可以用y、n控制是否开启该功能,需要填写相关数据库等信息,比较好懂,在此不多说。

cat >> backupmysql.conf << "EOF"
# William Guozi
# https://www.cnblogs.com/William-Guozi, williamguozi.github.io
# You are free to modify and distribute this code,
# so long as you keep my name and URL in it. # your MySQL server's name
SERVER=`hostname -f` # directory to backup to
BACKDIR=/home/rdsbackup # date format that is appended to filename
DATE=`date -u +'%F-%T'`
#----------------------MySQL Settings--------------------# DBNAMES[0]="db1 db2 db3" # databases you want to backup, separated by a space; leave empty to backup all databases on this host
DBUSER[0]="username" # MySQL username
DBPASS[0]='password' # MySQL password
DBHOST[0]="localhost" # your MySQL server's location (IP address is best)
DBPORT[0]="3306" # MySQL port
DBTABLES[0]="" # tables you want to backup or exclude, separated by a space; leave empty to back up all tables
DBTABLESMATCH[0]="include" # include will backup ONLY the tables in DBTABLES, exclude will backup all tables BUT those in DBTABLES
DBOPTIONS[0]="--quick --single-transaction" #----------------------Mail Settings--------------------# # set to 'y' if you'd like to be emailed the backup (requires mutt)
MAIL=y # email addresses to send backups to, separated by a space
EMAILS="ops@glinux.cn"
SUBJECT="$DBNAMES[0] Backup On $SERVER ($DATE)" #----------------------Weixin Settings--------------------# # set to 'y' if you'd like to be emailed the backup (requires mutt)
WEIXIN=n # email addresses to send backups to, separated by a space
CropID='wwc791b89a193451a'
Secret='3YwOqQ85VTYc3K6rbwKcFlMmwjbW39KeE-Cd6SMEA'
#也就是agentid
AppID=1000002
##也就是用户的唯一表示id
UserID=@all
##也就是联系人的组id
PartyID=1
WeChatMsg="$DBNAMES Backup On $SERVER ($DATE)" #----------------------Duplicity Settings--------------------# DUPLICITY=n
DUPLICITY_OPTIONS="--no-encryption -v8 --s3-use-new-style"
DUPLICITY_TARGET_URL="s3+http://my-backups/db/" #----------------------S3 Settings--------------------# S3_UPLOAD=n
S3_PATH="my-backups/db/"
S3_OPTIONS=""
AWS_CLI_OPTIONS="--region us-east-1" #----------------------FTP Settings--------------------# # set "FTP=y" if you want to enable FTP backups
FTP=n # FTP server settings; group each remote server using arrays
# you can have unlimited remote FTP servers
FTPHOST[0]="ftphostip"
FTPUSER[0]="username"
FTPPASS[0]="password"
FTPDIR[0]="backups"
FTPPORT[0]="21" # directory to backup to; if it doesn't exist, file will be uploaded to
# first logged-in directory; the array indices correspond to the FTP info above #-------------------Deletion Settings-------------------# # delete old files?
DELETE=y # how many days of backups do you want to keep?
DAYS=7 #-------------------Compression Settings-------------------# COMPRESSION_COMMAND="gzip -f -9"
COMPRESSION_EXTENSION="gz"
#----------------------End of Settings------------------#

mysql备份脚本

其中微信发送部分为添加部分,原版请查看参考文档。

#! /bin/bash
PATH=$PATH:/usr/local/mysql/bin # William Guozi
# https://www.cnblogs.com/William-Guozi, williamguozi.github.io
# You are free to modify and distribute this code,
# so long as you keep my name and URL in it. #----------------------Start of Script------------------# function die () {
echo >&2 "$@"
exit 1
} CONFIG=${1:-`dirname $0`/backupmysql.conf}
[ -f "$CONFIG" ] && . "$CONFIG" || die "Could not load configuration file ${CONFIG}!" # check of the backup directory exists
# if not, create it
if [ ! -d $BACKDIR ]; then
echo -n "Creating $BACKDIR..."
mkdir -p $BACKDIR
echo "done!"
fi for KEY in "${!DBHOST[@]}"; do
echo "Backing up MySQL database on ${DBHOST[$KEY]}..." if [ -z "${DBNAMES[$KEY]}" ]; then
echo -n "Creating list of all your databases..."
DBS=`mysql -h ${DBHOST[$KEY]} --user=${DBUSER[$KEY]} --password=${DBPASS[$KEY]} -Bse "show databases;"`
echo "done!"
else
DBS=${DBNAMES[$KEY]}
fi # filter out the tables to backup
if [ -n "${DBTABLES[$KEY]}" ]; then
if [ ${DBTABLESMATCH[$KEY]} = "exclude" ]; then
TABLES=''
for table in ${DBTABLES[$KEY]}; do
TABLES="$TABLES --ignore-table=$table "
done
else
TABLES=${DBTABLES[$KEY]}
fi
fi start_time=`date +%T`
Beijing_start_time=`date -u -d "$start_time -0800"`
for database in $DBS; do
echo -n "Backing up database $database..."
test ${DBHOST[$KEY]} = "localhost" && SERVER=`hostname -f` || SERVER=${DBHOST[$KEY]}
mysqldump --host ${DBHOST[$KEY]} --port ${DBPORT[$KEY]} --user=${DBUSER[$KEY]} --password=${DBPASS[$KEY]} \
${DBOPTIONS[$KEY]} $database $TABLES > $BACKDIR/$SERVER-$database-$DATE-mysqlbackup.sql
$COMPRESSION_COMMAND $BACKDIR/$SERVER-$database-$DATE-mysqlbackup.sql
echo "done!"
done
done # end_time=date -u -d "`date +%T` -0800"
end_time=`date +%T`
Beijing_end_time=`date -u -d "$end_time -0800"`
# if you have the mail program 'mutt' installed on
# your server, this script will have mutt attach the backup
# and send it to the email addresses in $EMAILS
####delete database not in this machine
# find $BACKDIR -size -4k |xargs rm -rf if [ $MAIL = "y" ]; then
BODY="你的备份已经完毕! backup start at $Beijing_start_time,end at $Beijing_end_time \n\n"
BODY=$BODY`cd $BACKDIR; for file in *$DATE-mysqlbackup.sql.$COMPRESSION_EXTENSION; do echo "md5值是"; md5sum ${file}&&du -sh ${file}|awk '{print $1}'; done`
ATTACH=`for file in $BACKDIR/*$DATE-mysqlbackup.sql.$COMPRESSION_EXTENSION; do echo -n "-a ${file} "; done` echo -e "$BODY" | mutt -s "$SUBJECT" -- $EMAILS
if [[ $? -ne 0 ]]; then
echo -e "ERROR: Your backup could not be emailed to you! \n";
else
echo -e "Your backup has been emailed to you! \n"
fi
fi # send by weixin
if [ $WEIXIN = "y" ];then
GURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$CropID&corpsecret=$Secret"
Gtoken=$(/usr/bin/curl -s -G $GURL | awk -F\" '{print $10}')
PURL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$Gtoken"
function body() {
printf '{\n'
printf '\t"touser": "'"$UserID"\"",\n"
printf '\t"toparty": "'"$PartyID"\"",\n"
printf '\t"msgtype": "text",\n'
printf '\t"agentid": "'"$AppID "\"",\n"
printf '\t"text": {\n'
printf '\t\t"content": "'"$WeChatMsg"\""\n"
printf '\t"},\n'
printf '\t"safe:":0\n'
printf '}\n'
}
/usr/bin/curl --data-ascii "$(body)" $PURL
fi if [ $DELETE = "y" ]; then
OLDDBS=`cd $BACKDIR; find . -name "*-mysqlbackup.sql.$COMPRESSION_EXTENSION" -mtime +$DAYS`
REMOVE=`for file in $OLDDBS; do echo -n -e "delete ${file}\n"; done` # will be used in FTP cd $BACKDIR; for file in $OLDDBS; do rm -v ${file}; done
if [ $DAYS = "1" ]; then
echo "Yesterday's backup has been deleted."
else
echo "The backups from $DAYS days ago and earlier have been deleted."
fi
fi if [ $DUPLICITY = "y" ]; then
duplicity full --progress $DUPLICITY_OPTIONS $BACKDIR $DUPLICITY_TARGET_URL
fi if [ $S3_UPLOAD = "y" ]; then
aws $AWS_CLI_OPTIONS s3 sync $BACKDIR s3://$S3_PATH $S3_OPTIONS
fi if [ $FTP = "y" ]; then
echo "Initiating FTP connection..." cd $BACKDIR
ATTACH=`for file in *$DATE-mysqlbackup.sql.$COMPRESSION_EXTENSION; do echo -n -e "put ${file}\n"; done` for KEY in "${!FTPHOST[@]}"; do
echo -e "\nConnecting to ${FTPHOST[$KEY]} with user ${FTPUSER[$KEY]}..."
ftp -nvp <<EOF
open ${FTPHOST[$KEY]} ${FTPPORT[$KEY]}
user ${FTPUSER[$KEY]} ${FTPPASS[$KEY]}
binary
tick
mkdir ${FTPDIR[$KEY]}
cd ${FTPDIR[$KEY]}
$REMOVE
$ATTACH
quit
EOF
done echo -e "FTP transfer complete! \n"
fi echo "Your backup is complete!"

制定定时任务

crontab -l
00 14 * * * bash /data/scripts/backupmysql.sh

效果展示

下图为微信收到的报告信息

参考文档

Mysql:自动化备份的更多相关文章

  1. mysql互为主从实战设置详解及自动化备份(Centos7.2)

    mysql互为主从实战设置详解(Centos7.2) 第一步:mysql配置  my.cnf配置 服务器1 (10.89.10.90) [mysqld]  server-id=1  log-bin=/ ...

  2. MySQL定时备份数据库

    一.MySQL数据备份 1.1. mysqldump命令备份数据 在MySQL中提供了命令行导出数据库数据以及文件的一种方便的工具mysqldump,我们可以通过命令行直接实现数据库内容的导出dump ...

  3. mysql数据备份及恢复

    备份工具 mysqldump mysqldump是mysql和mariadb上最好的备份工具之一,免费开源. mysqldump 首先查询每个数据库和每个表的结构与数据,然后把查出的所有内容导出到文本 ...

  4. mysql 数据备份与数据导入到出

    一.数据备份 #1. 物理备份: 直接复制数据库文件,适用于大型数据库环境.但不能恢复到异构系统中如Windows. #2. 逻辑备份: 备份的是建表.建库.插入等操作所执行SQL语句,适用于中小型数 ...

  5. MySQL定时备份数据库(全库备份)

    一.MySQL数据备份 1.1. mysqldump命令备份数据 在MySQL中提供了命令行导出数据库数据以及文件的一种方便的工具mysqldump,我们可以通过命令行直接实现数据库内容的导出dump ...

  6. 部署MySQL自动化运维工具inception+archer

    ***************************************************************************部署MySQL自动化运维工具inception+a ...

  7. mysql数据备份与操作

    物理备份: 直接复制数据库文件,适用于大型数据库环境.但不能恢复到异构系统中如Windows. 逻辑备份: 备份的是建表.建库.插入等操作所执行SQL语句,适用于中小型数据库,效率相对较低. 导出表: ...

  8. 有赞MySQL自动化运维之路—ZanDB

      有赞MySQL自动化运维之路—ZanDB 一.前言 在互联网时代,业务规模常常出现爆发式的增长.快速的实例交付,数据库优化以及备份管理等任务都对DBA产生了更高的要求,单纯的凭借记忆力去管理那几十 ...

  9. SQL学习笔记六之MySQL数据备份和pymysql模块

    mysql六:数据备份.pymysql模块   阅读目录 一 IDE工具介绍 二 MySQL数据备份 三 pymysql模块 一 IDE工具介绍 生产环境还是推荐使用mysql命令行,但为了方便我们测 ...

  10. MySQL数据备份与还原(mysqldump)

    一 mysqldump指令实现数据备份.mysql指令实现数据还原 经常有朋友问我,DBA到底是做什么的,百科上说:数据库管理员(Database Administrator,简称DBA),是从事管理 ...

随机推荐

  1. Date、Time类型拼接成字符串

    Date.Time类型拼接成字符串 语言用的是kotlin,和Java类似 var time = "" val sdf1 = SimpleDateFormat("yyyy ...

  2. InnoDB与MyISAM的区别(高性能MySQL笔记)

    1.InnoDB支持事务,MyISAM不支持,也就是说MyISAM不支持事务回滚操作,这个功能可能是致命的 2.InnoDB支持行锁,MyISAM只支持表锁,不过InnoDB的行锁是建立在索引之上的, ...

  3. 原型,原型链,给予原型和class的继承

    学习react的时候遇到了class方式的继承语法,原理和代码的解释很详细,值得一读. 原型每个函数(构造函数)都有一个 prototype 属性,指向该函数(构造函数)的原型对象.实例没有 prot ...

  4. 体验.NET Core 命令行应用程序-CommandLineUtils

    前言 在我们开发中可能需要设计一次性应用程序,这些实用程序可以利用接近原始源代码的优势,但可以在与主Web应用程序完全独立的安全性上下文中启动.具体在 [管理过程](https://12factor. ...

  5. 2019年面试官最喜欢问的28道ZooKeeper面试题

    前言 ZooKeeper 是一个分布式的,开放源码的分布式应用程序协调服务.它是一个为分布式应用提供一致性服务的软件,提供的功能包括:配置维护.域名服务.分布式同步.组服务等. ZooKeeper 的 ...

  6. 图解kubernetes服务打散算法的实现源码

    在分布式调度中为了保证服务的高可用和容灾需求,通常都会讲服务在多个区域.机架.节点上平均分布,从而避免单点故障引起的服务不可用,在k8s中自然也实现了该算法即SelectorSpread, 本文就来学 ...

  7. DP- 01背包问题

    这个01背包 , 理解了一天才勉强懂点 , 写个博客  (  推荐   http://blog.csdn.net/insistgogo/article/details/8579597) 题目 : 有N ...

  8. ntelliJ IDEA添加注释常用的快捷键

    IDEA可以使用快捷键添加行注释Ctrl+/.块注释Ctrl+Shift+/,还可以快速生成类注释.方法注释等,下面就介绍这几种快捷键的用法

  9. Mysql的binlog日志与mysqlbinlog命令

    binlog相关 MySQL 的二进制日志 binlog 可以说是 MySQL 最重要的日志,它记录了所有的 DDL 和 DML 语句(除了数据查询语句select.show等),以事件形式记录,还包 ...

  10. 20190925Java课堂记录(一)

    判断字符串是否回文 设计思想 利用递归,每次返回长度减二的字符串,最终返回结果 源程序代码 import java.util.Scanner; public class palindrome { st ...