Mysql定时备份指南
1、登录数据库服务器,创建目录
mkdir -p /data/mysqlbak/data
mkdir -p /data/mysqlbak/scripts
mkdir -p /data/mysqlbak/logs
2、创建备份脚本文件
Vi backup.sh
脚本文件:
#!/bin/bash
#备份目录
BACKUP_ROOT=/data/mysqlbak
BACKUP_FILEDIR=$BACKUP_ROOT/data
#当前日期
DATE=$(date +%Y%m%d)
######备份######
#查询所有数据库
#-uroot -p123456表示使用root账号执行命令,且root账号的密码为:123456
DATABASES=$(mysql -uroot -p123456 -e "show databases" | grep -Ev "Database|sys|information_schema|performance_schema|mysql")
#循环数据库进行备份
for db in $DATABASES
do
echo
echo ----------$BACKUP_FILEDIR/${db}_$DATE.sql.gz BEGIN----------
mysqldump -uroot -p123456 --default-character-set=utf8 -q --lock-all-tables --flush-logs -E -R --triggers -B ${db} | gzip > $BACKUP_FILEDIR/${db}_$DATE.sql.gz
#文件赋权
cd /data/mysqlbak/
chmod -R 777 data/
#异地备份
echo ----------$BACKUP_FILEDIR/${db}_$DATE.sql.gz COMPLETE----------
echo ----------scp 226 begin----------
expect -c "
spawn scp -r /data/mysqlbak/data/${db}_$DATE.sql.gz [email protected]:/data/mysqlbak/data123/
expect {
\"*password*\" {set timeout 300; send \"此处是scp的密码(需要备份到第三服务的登录密码)\r\"; exp_continue;}
\"yes/no\" {send \"yes\r\";}
}
expect eof"
echo ----------scp 226 end----------
echo
done
echo "done"
3、创建删除脚本文件
vi backup_clean.sh
脚本文件:
#!/bin/bash
echo ----------CLEAN BEGIN----------
find /data/mysqlbak/data -mtime +7 -name "*.gz" -exec rm -rf {} \;
echo ----------CLEAN COMPLETE----------
注意:7代表保存7天的数据,循环删除
4、给脚本赋权
chmod 777 backup.sh
chmod 777 backup_clean.sh
5、添加liunx定时任务
执行命令:crontab -e
输入:
00 2 * * * /data/mysqlbak/scripts/backup.sh > /data/mysqlbak/logs/backup.log 2>&1
00 1 * * * /data/mysqlbak/scripts/backup_clean.sh > /data/mysqlbak/logs/backup_full_clean.log 2>&1
注意:00 2 * * *标识每天2点执行
6、查看定时任务
执行命令:crontab -l
7、安装expect
有线安装:在线安装 yum install -y expect
离线安装:
expect依赖tcl库
安装包:
https://files.cnblogs.com/files/tozh/tcl8.4.11-src.tar.gz
https://files.cnblogs.com/files/tozh/expect-5.43.0.tar.gz
我将两个压缩包传到了/opt/目录下
1,安装tcl
tar xf tcl8.4.11-src.tar.gz
cd tcl8.4.11/unix
./configure
make && make install
2,安装expect
tar xf expect-5.43.0.tar.gz
cd expect-5.43.0
./configure --with-tclinclude=/opt/tcl8.4.11/generic --with-tclconfig=/usr/local/lib/
make && make install
8、在需要备份的服务器上创建备份目录
mkdir -p /data/mysqlbak/data123
9、如果报错:检查服务器安全配置信息
vi /etc/ssh/sshd_config
把 PermitRootLogin no 改成 PermitRootLogin yes
重启ssh服务:/etc/init.d/sshd restart
注意:两个主机都要修改
手动执行成功,定时执行报错,建立软连接
ln -s /usr/local/mysql-5.7.25/bin/mysql /usr/bin
ln -s /usr/local/mysql-5.7.25/bin/mysqldump /usr/bin
检查是否安装好(显示安装好的版本号就是已经安装好了)并创建软链接。
expect -v
[root@localhost shell]# expect -v
expect version 5.45.3
[root@localhost shell]# ln -s /usr/local/bin/expect /usr/bin/expect
标签:备份,gz,mysqlbak,expect,Mysql,----------,定时,data From: https://www.cnblogs.com/songqiang8858/p/16642496.html