87 lines
2.1 KiB
Bash
Executable File
87 lines
2.1 KiB
Bash
Executable File
#!/bin/bash
|
|
|
|
# Crontab line.
|
|
#0 2 * * * bash /root/backup.sh | tee -a /var/log/backup_$(date +"\%Y-\%m-\%d").log
|
|
|
|
# Exit on error.
|
|
# Because I've been grilled about not using this - phillw, I'm looking
|
|
# at you ;)
|
|
set -e
|
|
|
|
# Where do we locally store the backups?
|
|
BACKUP_STORE='/backup'
|
|
|
|
# What directories do we backup?
|
|
# Each _full_ path must be seperated by a space. If a path uses a
|
|
# special char e.g, space or non-alphanumeric chars escape it with a
|
|
# backslash.
|
|
BACKUP_DIRS='/etc /home /var/www /root'
|
|
|
|
# A date string for file/folder-names.
|
|
SCRIPT_RUN_DATE=`date '+%Y-%m-%d-%H-%M'`
|
|
|
|
# Backup the above $BACKUP_DIRS. Set to 0 to disable.
|
|
BACKUP_DIRECTORIES_AND_FILES="1"
|
|
|
|
# CRON backup? Set to 0 to disable.
|
|
BACKUP_CRON="1"
|
|
|
|
# MARIADB/MYSQL dump backup? Set to 0 to disable.
|
|
BACKUP_SQL="1"
|
|
|
|
|
|
## Edit below at own risk..
|
|
if [[ $EUID -ne 0 ]]; then
|
|
echo 'run as root'
|
|
exit 1
|
|
fi
|
|
|
|
# Before we do anything, switch to our backup store directory.
|
|
cd "${BACKUP_STORE:-/tmp/$SCRIPT_RUN_DATE}"
|
|
|
|
# Now make our backup directory using the script_run_date.
|
|
BACKUP_CWD="./${SCRIPT_RUN_DATE:-fail}"
|
|
mkdir "${BACKUP_CWD}"
|
|
cd "${BACKUP_CWD}"
|
|
|
|
if [[ "$BACKUP_DIRECTORIES_AND_FILES" == "1" ]]; then
|
|
|
|
for OBJ in ${BACKUP_DIRS:-}; do
|
|
OBJ_S=${OBJ//\//-}
|
|
OBJ_S=${OBJ_S/-/}
|
|
|
|
if [[ ! -f "${OBJ}" ]]; then
|
|
if [[ ! -d "${OBJ}" ]]; then
|
|
printf "\n!! file or directory \"%s\" not found, skipping..\n" "${OBJ}"
|
|
continue;
|
|
fi
|
|
fi
|
|
|
|
tar -cJf "./$OBJ_S.tar.xz" "${OBJ}"
|
|
done
|
|
|
|
fi
|
|
|
|
if [[ "$BACKUP_SQL" == "1" ]]; then
|
|
|
|
DATABASES="$(echo "show databases" | mysql | grep -Ev "^(Database|mysql|performance_schema|information_schema)$" | paste -sd " " -)"
|
|
|
|
[[ -z "${DATABASES:-}" ]] && exit 1
|
|
|
|
for DB in $DATABASES; do
|
|
mysqldump --single-transaction --routines --events --triggers --lock-tables $DB > "./$DB.sql" || exit 1;
|
|
done
|
|
|
|
fi
|
|
|
|
if [[ "$BACKUP_CRON" == "1" ]]; then
|
|
|
|
for USER in $(cut -f1 -d: /etc/passwd); do
|
|
crontab -u $USER -l > "${USER}-cron.txt" || continue;
|
|
done
|
|
|
|
fi
|
|
|
|
echo "$SCRIPT_RUN_DATE OK" >> /var/log/$0-run.log
|
|
|