| 1 | Script to backup server using rsync over ssh, deployed on ticket:763 to wiki:ParrorServer, wiki:PenguinServer and wiki:PuffinServer. |
| 2 | |
| 3 | {{{ |
| 4 | #!/usr/bin/env bash |
| 5 | |
| 6 | # List of local directories to be backed up |
| 7 | # is contained in this file, one per line |
| 8 | BACKUP_LIST="/etc/agile/backup" |
| 9 | # The hostname of this server, used to create |
| 10 | # a directory on the remote server |
| 11 | HOSTNAME=$(hostname) |
| 12 | # The server to backup to, this is set in |
| 13 | # /root/.ssh/config |
| 14 | SSH_SERVER="backup" |
| 15 | # This script uses lockfile which comes with procmail |
| 16 | LOCKFILE_BINARY="/usr/bin/lockfile" |
| 17 | LOCKFILE="/var/run/lock/$(basename $0).lock" |
| 18 | # Write the outcome to this log |
| 19 | LOGFILE="/var/log/$(basename $0)" |
| 20 | |
| 21 | # Check that the script is being run by root |
| 22 | if [[ "$(id -u)" != "0" ]] ; then |
| 23 | echo "You must run '$0' as root or via sudo" |
| 24 | exit 1 |
| 25 | fi |
| 26 | |
| 27 | # Test if the lockfile binary can be found |
| 28 | if [[ ! -e "$LOCKFILE_BINARY" ]]; then |
| 29 | echo "$LOCKFILE_BINARY not found, please install the procmail package." |
| 30 | exit 1 |
| 31 | fi |
| 32 | |
| 33 | # if the $LOCKFILE exists then exit |
| 34 | # the lockfile is read only |
| 35 | # the timeout is set to 2 hours (7200 secs) |
| 36 | # if the lockfile is older than this it will be |
| 37 | # removed, this need to be improved so the log is uupdated |
| 38 | $LOCKFILE_BINARY -r 1 -l 7200 $LOCKFILE || exit 23 |
| 39 | |
| 40 | # Do the backup, first test that the file |
| 41 | # with the list of files to be backed up |
| 42 | # exists |
| 43 | if [[ -f ${BACKUP_LIST} ]]; then |
| 44 | for dir in $(<${BACKUP_LIST}); do |
| 45 | # Make the directory on the backup server |
| 46 | ssh ${SSH_SERVER} mkdir -p ${HOSTNAME}/${dir} |
| 47 | # Copy the files to the backup server |
| 48 | # Test for the scripts has been run with -v |
| 49 | # for verbose output |
| 50 | if [[ $1 == "-v" ]]; then |
| 51 | rsync -av --delete ${dir}/ ${SSH_SERVER}:${HOSTNAME}/${dir}/ |
| 52 | else |
| 53 | rsync -aq --delete ${dir}/ ${SSH_SERVER}:${HOSTNAME}/${dir}/ 2>&1 |
| 54 | fi |
| 55 | # catch errors |
| 56 | # http://idolinux.blogspot.co.uk/2008/08/bash-script-error-handling.html |
| 57 | if [ $? != 0 ]; then |
| 58 | { |
| 59 | echo "Backup Error at $(date +%c)" >> $LOGFILE |
| 60 | rm -vf $LOCKFILE |
| 61 | exit 23 |
| 62 | } fi |
| 63 | done |
| 64 | else |
| 65 | echo "$BACKUP_LIST doesn't exist" |
| 66 | echo "Backup Error at $(date +%c)" >> $LOGFILE |
| 67 | rm -vf $LOCKFILE |
| 68 | exit 23 |
| 69 | fi |
| 70 | |
| 71 | # Remove the lock file and update the log |
| 72 | rm -vf $LOCKFILE |
| 73 | echo "Backup Success at $(date +%c)" >> $LOGFILE |
| 74 | }}} |