(编辑:jimmy 日期: 2024/12/27 浏览:2)
我们使用过mysqldump都知道,使用该命令后,需要我们手动输入 mysql的密码,那么我们就不能够直接在crontab中使用mysqldump实现周期备份。其实我们可以使用expect脚本自动输入密码,从而实现真正的周期备份。如果你不知道什么是expect,建议先请看这篇文章:https://www.jb51.net/article/197865.htm
思路如下:
3.1、单机冷备份
(1)mysqldump的shell脚本
backup.sh:
#!/bin/bash mysql_username=$1 backup_databases=$2 backup_path=$3 mysqldump -u ${mysql_username} -p --databases ${backup_databases} > ${backup_path}
(2)执行mysqldump的expect脚本,能帮助我们自动输入mysql代码
single_cold_backup_service.exp:
#!/usr/bin/expect set timeout 5 #设置本机信息 set mysql_username [lindex $argv 0] set backup_database [lindex $argv 1] set backup_path [lindex $argv 2] #utils路径 set utils_path /home/hadoop/backup_script/utils spawn bash ${utils_path}/backup.sh ${mysql_username} ${backup_database} ${backup_path} expect { "*assword*" {send "nimabidecao1\r"} #输入密码 } expect eof
(3)驱动脚本,执行expect,这里可以传入需要的参数
single_cold_backup_service_driver.sh:
#!/bin/bash #这里的数据就可以写死了 mysql_username=root backup_databases=school backup_path=$HOME/backup_data/${backup_databases}.sql #运行expect脚本 expect $HOME/backup_script/single_cold_backup/single_cold_backup_service.exp ${mysql_username} ${backup_databases} ${backup_path}
这里一定要十分注意自己的路径,强烈建议使用绝对路径来执行
(4)使用crontab周期执行驱动脚本
进入crontab编辑:crontab -e
输入如下内容:
0 9 * * 1 bash /home/hadoop/backup_script/single_cold_backup/single_cold_backup_driver.sh
意思为:每周1早上9点执行一次备份
若你想确定自己想要的时间,可以到这个网址:https://crontab-generator.org/ 去点选自己想要的时间
3.2、双机冷备份
(1)复制远程文件,用于拷贝本地机的mysql备份文件
scp.sh:
#!/bin/bash local_backup_path=$1 another_user=$2 another_ip=$3 another_backup_path=$4 scp ${local_backup_path} ${another_user}@${another_ip}:${another_backup_path}
(2)执行mysqldump的expect脚本,能帮助我们自动输入mysql代码
double_cold_backup_service.exp:
#!/usr/bin/expect set timeout 5 #主机信息 set mysql_username [lindex $argv 0] set backup_database [lindex $argv 1] set backup_path [lindex $argv 2] #从机信息 set slave_user [lindex $argv 3] set slave_ip [lindex $argv 4] set slave_backup_path [lindex $argv 5] #utils路径 set utils_path /home/hadoop/backup_script/utils spawn bash ${utils_path}/backup.sh ${mysql_username} ${backup_database} ${backup_path} expect { "*assword*" {send "nimabidecao1\r"} #输入密码 } spawn bash ${utils_path}/scp.sh ${backup_path} ${slave_user} ${slave_ip} ${slave_backup_path} expect { "*assword*" {send "nimabidecao1\r"} #输入密码 } expect eof
(3)驱动脚本,执行expect,这里可以传入需要的参数
double_cold_backup_service_driver.sh:
#!/bin/bash #本机信息 mysql_username=root backup_databases=school backup_path=$HOME/backup_data/${backup_databases}.sql #从机信息 slave_user=meizhaowei slave_ip=172.20.10.14 slave_backup_path=backup_data/doule_cold_backup_data/${backup_databases}.sql #执行写绝对路径 expect $HOME/backup_script/double_cold_backup/double_cold_backup_service.exp ${mysql_username} ${backup_databases} ${backup_path} ${slave_user} ${slave_ip} ${slave_backup_path}
(4)使用crontab周期执行驱动脚本
0 9 * * 1 bash /home/hadoop/backup_script/double_cold_backup/double_cold_backup_driver.sh
意思是:每周1早上9点执行一次备份