shell 脚本远程备份mysql数据库

需求:使用mysqldump实现远程的mysql服务器备份数据

备份脚本服务器: 192.168.1.115
目标mysql服务器:192.168.1.12
脚本目录:/home/admin/mysql_backup
脚本名:mysql_backup.sh
数据目录:/home/admin/mysql_backup/data

脚本代码如下

----------------------------------------------------------------------------------------

#!/bin/bash

#####################
# mysql 备份脚本           #
#                                    #
#####################

# 备份目录
base_path='/home/admin/mysql_backup/data'

# 备份时间
backup_date=$(date -d now "+%y%m%d-%H%m")

# remote host
remote_host="192.168.1.12"
remote_user="admin"
remote_passwd="123456"
remote_database="mydatabase"

# 保留天数
KEEP_DAYS=10

############################################
logs_path=${base_path}
log_name=${base_path}/${backup_date}.log
file_name=${base_path}/${backup_date}.sql

touch ${log_name}

echo 'start !!' > ${log_name}

retry_times=5

# 是否执行成功
function overdump {
  echo "mysqldump exec status : $? , retry_times : ${retry_times} "  >> ${log_name}
  if [[ $? -eq 0 ]];then
        echo "backuped successful !!" >> ${log_name}
  else
        echo "backup is running !!" >> ${log_name}
        if [ ${retry_times} -eq 0 ];then
            echo "retry_times is over!mysqldump is not find or system is busy !!" >> ${log_name}
            exit
        fi
         /bin/sleep 10
        retry_times=$[ ${retry_times} - 1]
        overdump
  fi
}

# mysql dump脚本
mysqldump -h ${remote_host} -u ${remote_user} -p${remote_passwd} ${remote_database} --default-character-set=utf8| gzip > ${file_name}.gz
overdump

echo "${file_name} backup!!!" >> ${log_name}

# 日志删除 10天前修改的删除
if [ -d "${logs_path}" ]; then
    find "${logs_path}" -type f -name "*.*" -mtime +${KEEP_DAYS} -exec rm -f {} \;
fi

echo "rm log over!!" >> ${log_name}

###########################################################################
#                                                                                                                                                  #
# 定时任务设置  每天0点30分                                                                                                     #
# 30 0 * * * /bin/sh /home/admin/mysql_backup/mysql_bakup.sh                                              #
#                                                                                                                                                  #
###########################################################################

你可能感兴趣的:(linux,linux基础)