shell - 物理备份

2022-06-05
#!/bin/bash
# 备份数据,demo:/opt/bin/backup.sh -n nexus -b /volume1/backup -i 192.168.150.132 -s 22 -u root -d 3 -p /home/disk1/nexus-new/programs/nexus-3.5.1-02/
# 上传至oss,保留7天

today=$(date "+%Y%m%d")
yesterday=$(date +%Y%m%d --date='1 days ago')
sevenday=$(date +%Y%m%d --date='7 days ago')

function PushOss {
    cpu_nums=$(cat /proc/cpuinfo |grep -c name)
    time tar cf - ${main_path}/${today}/ | pigz -p ${cpu_nums} > ${backup_path}/${project_name}.tar.gz-${today}
    time ossutil64 rm oss://yqn-backup/${project_name}/${project_name}.tar.gz-${sevenday}
    time ossutil64 cp ${backup_path}/${project_name}.tar.gz-${today} oss://yqn-backup/${project_name}/
    rm ${backup_path}/${project_name}.tar.gz-${today}
}

while getopts "b:n:i:u:p:s:d:o::" opt
do
    case $opt in
            b ) backup_path=$OPTARG;; # 本地备份目录
            n ) project_name=$OPTARG;; # 项目名
            i ) remote_ip=$OPTARG;; # 远程服务器ip
            u ) remote_user=$OPTARG;; # ssh用到的远程用户
            p ) remote_path=$OPTARG;; # 远程服务器目录,需以/结尾
            s ) ssh_port=$OPTARG;; # ssh用到的端口
            d ) delete_day=$OPTARG;; # 本地保留的备份天数
            o ) pushoss=$OPTARG;; # 是否push至oss
            ? ) #当有不认识的选项的时候arg为?
            echo 'parameter is wrong!'
            exit 1;;
    esac
done


main_path=${backup_path}/${project_name}
local_backup_path=${main_path}/${today}/${remote_ip}${remote_path}
if [[ -d ${local_backup_path} ]];then
    rm -rf ${local_backup_path}
fi
mkdir -p ${main_path}
if [[ -d ${main_path}/${yesterday} ]] ;then
    if [[ ! -d ${main_path}/${today} ]];then
        cp -rf ${main_path}/${yesterday} ${main_path}/${today}
    fi
fi
mkdir -p ${local_backup_path}

sshpass -p sr@12345 /usr/bin/rsync -e "ssh  -o stricthostkeychecking=no -p ${ssh_port}" -av ${remote_user}@${remote_ip}:${remote_path}/ ${local_backup_path} --delete-after
if [[ ${pushoss} == "yes" ]];then
    PushOss
fi
if [[ $? -eq 0 ]];then
    find ${backup_path}/${project_name} -maxdepth 1 -mindepth 1 -type d -ctime +${delete_day} | xargs rm -rf
else
    echo "send dingding"
    exit 1
fi