Crontab을 통한 백업(Rsync), 디스크검사하기 및 이메일 알림

Nextcloud를 이용한 동기화를 사용한다고 하더라도

별개로 일주일이나 한달마다 데이터 손실을 방지하기 위해 백업을 설정하는 것이 좋다.

백업을 손쉽고 빠르게 하기 위해서 rsync라는 패키지를 이용해서 간단한 백업을 구성하고

이를 crontab을 이용해서 주기적으로 실행하고, 이메일알림을 받는 방법을 알아보자.

우선 rsync을 설치한다.

sudo apt-get install -y rsync

그 후 임의의 위치에

sudo vim <스크립트이름>.sh

를 통해 스크립트파일을 생성한뒤,

#!/bin/bash

# Script to backup personal files to the external USB drive.
# Specify the mount point here (DO NOT end mount_point with a forward-slash).
mount_point=<백업을 저장할 마운트위치>

echo "#####"
echo ""
# Check whether target volume is mounted, and mount it if not.
if ! mountpoint -q ${mount_point}/; then
     echo "Mounting the external USB drive."
     echo "Mountpoint is ${mount_point}"
     if ! mount ${mount_point}; then
        echo "An error code was returned by mount command!"
        exit 5
     else echo "Mounted successfully.";
     fi
else echo "${mount_point} is already mounted.";
fi
# Target volume **must** be mounted by this point. If not, die screaming.
if ! mountpoint -q ${mount_point}/; then
     echo "Mounting failed! Cannot run backup without backup volume!"
     exit 1
fi

echo "Preparing to transfer differences using rsync."

# Use the year to create a new backup directory each year.
# current_year=`date +%Y`
# Now construct the backup path, specifying the mount point followed by the path
# to our backup directory, finishing with the current year.
# (DO NOT end backup_path with a forward-slash.)
# backup_path=${mount_point}'/rsync-backup/'${current_year}
backup_path=${mount_point}'/rsync-backup'

echo "Backup storage directory path is ${backup_path}"

echo "Starting backup of <백업할 디렉토리> . . . "
mkdir --parents ${backup_path}/<백업위치>
# This time use the -a flag with the tee command, so that it appends to the end
# of the rsync-output.txt file rather than start a new file from scratch.
sudo rsync --archive --verbose --human-readable --itemize-changes --progress --no-o --no-g \
--delete --delete-excluded \
<백업할 디렉토리>/ ${backup_path}/<백업위치>/ 2>&1 | tee -a /backup/log/<백업위치>.txt

echo ""
echo "####"

tail /backup/log/<백업위치>.txt |  mail -a "From: Backup" -s "문서 백업 완료" <이메일주소>

를 수정해 저장해준다.

<백업을 저장할 마운트위치>는 USB나 외장하드의 마운트위치를 말한다.

<백업할 디렉토리>는 백업을 실행할 디텍토리를 얘기하고

<백업위치>는 백업이 저장될 디렉토리를 의미한다. (마운트위치/rsync-backup/ 아래에 생성되는 디렉토리다)

그 후

sudo chmod +x <스크립트이름>.sh

를 통해서 실행 권한을 부여한 뒤,

sudo crontab -e

명령어를 통해 crontab 에디터를 열어준다.

그 후 crontab정보를 참고해 주기를 설정한 뒤 커맨드 스크립트의 총경로를 추가한뒤 저장해준다.

ex) 30 5 * * 1 /usr/local/bin/script/<스크립트이름>.sh

 

그 후 주기적인 디스크 검사를 위해서

sudo apt-get install smartmontools

명령어를 통해 smartctl를 설치해준다.

그 후 crontab 에디터를 열어 주기를 설정한 뒤,

/usr/sbin/smartctl -H -l selftest -l error /dev/sdb | mail -a "From: DiskCheck" -s "주간 디스크 검사 결과" <이메일주소>

를 추가해주면 일정주기마다 디스크검사를 한뒤 이메일로 그 내용이 알림이 가게 된다.

 

[ezcc]

답글 남기기

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.