数据是非常重要的,所以数据备份必不可少!比如受到攻击,或者人为误操作时,备份数据就派上用场,及时恢复数据,将影响降到最低。下面以MySQL为例,利用mysqldump(mysql自带工具)工具进行备份,实现每天整点定时备份数据库(定时是利用linux的crontab,可以自己配置任意时间),并且只保留7天(时间可配置)
假设数据库名为:test
mkdir /usr/local/mysql_backup/dump;
(1)cd mkdir /usr/local/mysql_backup;
(2)vim mysql_backup.sh
内容如下(备份数据库test):
#!/bin/bash
# 设置mysql登录用户名和密码
mysql_user=""
mysql_password=""
mysql_host=""
mysql_port=""
mysql_charset="utf8mb4"
# 备份存放地址
backup_location=/usr/local/mysql_backup/dump
log_location=/usr/local/mysql_backup/log.log
# 是否删除过期数据
expire_backup_delete="ON"
expire_days=7
backup_time=`date +%Y-%m-%d_%H%M`
backup_dir=$backup_location
welcome_msg="===============into MySQL backup sh================"
# 判断mysql实例是否正常运行
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 $(date "+%Y-%m-%d %H:%M:%S") "ERROR:MySQL is not running! backup stop!">> $log_location
exit
else
echo $(date "+%Y-%m-%d %H:%M:%S") $welcome_msg>> $log_location
fi
# 备份指定数据库中数据
echo $(date "+%Y-%m-%d %H:%M:%S") "begin dump db test">> $log_location
mysqldump -h$mysql_host -P$mysql_port -u$mysql_user -p$mysql_password -B test> $backup_dir/test_$backup_time.sql
flag=`echo $?`
if [ $flag == "0" ];then
echo $(date "+%Y-%m-%d %H:%M:%S") "database test success backup">> $log_location
else
echo $(date "+%Y-%m-%d %H:%M:%S") "database test backup fail!">> $log_location
fi
# 删除过期数据
if [ "$expire_backup_delete" == "ON" -a "$backup_location" != "" ];then
`find $backup_location/ -type f -mtime +$expire_days | xargs rm -rf`
echo $(date "+%Y-%m-%d %H:%M:%S") "Expired backup data delete complete!">> $log_location
fi
(1)crontab -e
添加(每个整点执行备份):00 */1 * * * /usr/local/mysql_backup/mysql_backup.sh >> /usr/local/mysql_backup/log.log
(2)service crond restart;
如果需要恢复数据库到某个时间点的话,执行:
mysql -hhost -Pport -uroot -ppassword test< /usr/local/mysql_backup/dump/文件名.sql
目录
生成的备份文件