添加计划的shell脚本:
#!/bin/bash ############################################################################### # This script is used to generate backup crontab tasks. Please ensure that # # the backup node can access remote resources without password via SSH. # # The current running user is 'root', the backup directory is '/backup', # # and the running time is a random time point at 0-3 o'clock every day. You # # can modify these configurations if necessary. # # -- Programmed by WangXiaoLei on 17/02/2022 # ############################################################################### randNumHour=$(($RANDOM%3)) randNumMinute=$(($RANDOM%60)) user=root if [[ ${1%*/} == ${1:0:-1} ]] then remoteHost=`echo ${1%*/} | awk -F '@|:' '{print $2}'` remoteHostPath=`echo ${1%*/} | awk -F ':' '{print $2}'` else remoteHost=`echo $1 | awk -F '@|:' '{print $2}'` remoteHostPath=`echo $1 | awk -F ':' '{print $2}'` fi if [[ $1 == *"@"*":"* ]] then remoteHostFolder=${remoteHostPath%*`echo $remoteHostPath | awk -F '/' '{print $NF}'`} if ping -c 1 $remoteHost >/dev/null then if ssh `echo $1 | awk -F ':' '{print $1}'` "ls -l $remoteHostPath" then if crontab -l | grep $remoteHost | grep $remoteHostPath then echo -e "\033[31mThis crontab already exists!\033[0m" fi while true do read -r -p "Are You Sure Add crontab? [Y/n] " input case $input in [yY][eE][sS]|[yY]) mkdir -p /backup/$remoteHost$remoteHostFolder echo $randNumMinute" "$randNumHour" * * * /usr/bin/scp -r $1 /backup/$remoteHost$remoteHostFolder" >> /var/spool/cron/$user chmod 600 /var/spool/cron/$user crontab /var/spool/cron/$user /bin/systemctl restart crond.service exit 1 ;; [nN][oO]|[nN]) exit 1 ;; *) echo "Invalid input..." ;; esac done else echo -e "\033[31m$1 backup resource can not be found!\033[0m" fi else echo -e "\033[31m$remoteHost is unreachable!\033[0m" fi else echo "Usage: ./SetBackupCrond.sh <User@Host:FilePath>" fi
每日整理备份数据的计划
47 15 * * * if [ -d "/backup-2d" ]; then rm -rf /backup-2d >/dev/null 2>&1; fi && if [ -d "/backup-1d" ];then mv /backup-1d /backup-2d > /dev/null 2>&1; fi && if [ -d "/backup" ];then mv /backup /backup-1d >/dev/null 2>&1; fi && for line in `crontab -l | grep "/usr/bin/scp" | awk '{print $9}'`;do mkdir -p $line; done >/dev/null 2>&1