#!/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. #
# This script can also create a daily backup management crontab task, and #
# do the daily backup management. #
# The current running user is 'root', the backup directory is '/backup', #
# the script location is '/root', and the backup 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
backupdir="/backup"
scriptLocation="/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 $backupdir/$remoteHost$remoteHostFolder
echo $randNumMinute" "$randNumHour" * * * /usr/bin/scp -r $1 $backupdir/$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
elif [[ $1 == "SetDailyCleaning" ]]
then
if crontab -l | grep "DoDailyCleaning"
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])
echo "50 23 * * * /bin/bash $scriptLocation/SetBackupCrond.sh DoDailyCleaning >/dev/null 2>&1" >> /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
elif [[ $1 == "DoDailyCleaning" ]]
then
if [ -d "$backupdir-2d" ]
then rm -rf $backupdir-2d >/dev/null
fi
if [ -d "$backupdir-1d" ]
then mv $backupdir-1d $backupdir-2d > /dev/null
fi
if [ -d "$backupdir" ]
then mv $backupdir $backupdir-1d >/dev/null
fi
for line1 in `cat "/var/spool/cron/$user" | grep "/usr/bin/scp" | awk '{print $9}'`; do mkdir -p $line1
done
else
echo "Usage: ./SetBackupCrond.sh or ./SetBackupCrond.sh SetDailyCleaning"
fi