centos7下每天⾃动备份mysql数据库centos7下每天⾃动备份mysql数据库
1、新建备份脚本
vim /home/mysqlbak/mysql_bak.sh填⼊以下内容:
#!/bin/bash
mysql_user="USER"#MySQL备份⽤户
mysql_password="PASSWORD"#MySQL备份⽤户的密码
mysql_host="localhost"
mysql_port="3306"
mysql_charset="utf8"#MySQL编码
backup_db_arr=("db1""db2")#要备份的数据库名称,多个⽤空格分开隔开如("db1" "db2" "db3")
backup_location=/home/mysqlbak #备份数据存放位置,末尾请不要带"/",此项可以保持默认,程序会⾃动创建⽂件夹
expire_backup_delete="ON"#是否开启过期备份删除 ON为开启 OFF为关闭
expire_days=5 #过期时间天数默认为五天,此项只有在expire_backup_delete开启时有效
backup_time=`date +%Y%m%d%H%M`#定义备份详细时间
backup_Ymd=`date +%Y-%m-%d`#定义备份⽬录中的年⽉⽇时间
backup_3ago=`date -d '3 days ago' +%Y-%m-%d`#3天之前的⽇期
backup_dir=$backup_location/$backup_Ymd#备份⽂件夹全路径
welcome_msg="Welcome to use MySQL backup tools!"#欢迎语
mysql_ps=`ps -ef |grep mysql |wc -l`
mysql_listen=`netstat -an |grep LISTEN |grep $mysql_port|wc -l`
if[[$mysql_ps== 0] -o [$mysql_listen== 0]];then
echo"ERROR:MySQL is not running! backup stop!"
exit
else
echo$welcome_msg
fi
mysql -h$mysql_host -P$mysql_port -u$mysql_user -p$mysql_password<<end
use mysql;
select host,user from user where user='root' and host='localhost';
exit
end
flag=`echo $?`
if[$flag!="0"];then
echo"ERROR:Can't connect mysql server! backup stop!"
exit
之前下过mysql现在重新下载mysqlelse
echo"MySQL connect ok! "
# 判断有没有定义备份的数据库,如果定义则开始备份,否则退出备份
if["$backup_db_arr"!=""];then
#dbnames=$(cut -d ',' -f1-5 $backup_database)
#echo "arr is (${backup_db_arr[@]})"
for dbname in${backup_db_arr[@]}
do
echo"database $dbname "
`mkdir -p $backup_dir`
`mysqldump -h$mysql_host -P$mysql_port -u$mysql_user -p$mysql_password $dbname --default-character-set=$mysql_charset |gzip> $ backup_dir/$dbname-$backup_`
flag=`echo $?`
if[$flag=="0"];then
echo"database $dbname success backup to $backup_dir/$dbname-$backup_"
else
echo"database $dbname backup fail!"
fi
done
else
echo"ERROR:No database to backup! backup stop"
exit
fi
# 如果开启了删除过期备份,则进⾏删除操作
if["$expire_backup_delete"=="ON" -a "$backup_location"!=""];then
#`find $backup_location/ -type d -o -type f -ctime +$expire_days -exec rm -rf {} \;`
`find $backup_location/ -type d -mtime +$expire_days |xargs rm -rf`
echo"Expired backup data delete complete!"
fi
echo"All database backup success! Thank you!"
exit
fi
2、修改mysql_bak.sh脚本属性,赋予执⾏权限
chmod 600 /home/mysqlbak/mysql_bak.sh
chmod +x /home/mysqlbak/mysql_bak.sh
3、定时执⾏备份脚本
输⼊如下命令:
crontab -e
在页⾯中编写如下内容:
00 3 * * * /home/mysqlbak/mysql_bak.sh
可实现每天凌晨三点⾃动执⾏第⼀步编写的脚本,备份mysql数据库到/home/mysqlbak,且只保留最近5天的数据库备份。启动定时任务:
/bin/systemctl start crond.service
列出⽤户的定时任务列表:crontab -l
备份的⽂件怎么查看:
zcat +⽇志名.gz来查看,还可以⽤ | grep 来进⾏筛选⾃⼰想要的⽇志信息
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论