Mysql备份并上传到固定的服务器
第一步,备份mysql
back_mysql_db.sh
#!/bin/bash
# 没有则创建
if [ ! -d "/home/wwwroot/default/mysqlbackups" ];then
mkdir -p "/home/wwwroot/default/mysqlbackups"
fi
# 备份数据库
mysqldump -uroot -p123456 dbname > /home/wwwroot/default/mysqlbackups/dbname_$(date +%Y%m%dH%M%S).sql
# 只保留3天的数据库
find /home/wwwroot/default/mysqlbackups/ -type f -ctime +3 -exec rm -rf {} \;
第二步,将文件夹scp到服务器
scp_back_to_test.sh
需要安装一下expect
yum install expect
#!/usr/bin/expect
set user root
set password 123456
set dir /home/wwwroot/default/
set ip xxx.xxx.xxx
set files [lrange $argv 0 0]
spawn scp -r ${files} ${user}@${ip}:${dir}
expect {
"*yes/no*" { send "yes\r"; exp_continue}
"*password:*" { send "$password\r"; exp_continue }
}
interact
tips:默认情况下 10 秒执行命令就会中断,set timeout 120 能够设置执行时长
#!/usr/bin/expect
set user root
set password 123456
set dir /home/wwwroot/default/
set ip xxx.xxx.xxx
set files [lrange $argv 0 0]
#设置时长
set timeout 600
spawn scp -r ${files} ${user}@${ip}:${dir}
expect {
"*yes/no*" { send "yes\r"; exp_continue}
"*password:*" { send "$password\r"; exp_continue }
}
interact
第三步,配置定时器crontab
00 03 * * * sh /home/cron/back_mysql_db.sh >> /tmp/back_mysql_db.log 2>&1
30 03 * * * /home/cron/scp_back_to_test.sh /home/wwwroot/default/mysqlbackups/ >> /tmp/scp_back_to_test.log 2>&1
每天夜里3点半
第四步, 再来一个定期处理服务器超过三天的sql
clear_old_mysql_db.sh
#!/bin/bash
# 只保留5天的数据库
find /home/wwwroot/default/mysqlbackups/ -type f -ctime +5 -exec rm -rf {} \;
30 3 * * * sh /home/sh/clear_old_mysql_db.sh >> /tmp/clear_old_mysql_db.log 2 >&1