Backup Linux-сервера

Простой скритп бекапа данных с WEB-сервера на основе RSYNC

Нам понадобится:

  1. Сервер, куда будут складываться бекапы с установленым демоном rsync
  2. Простой скрипт бекапа (ниже)

Устанавливаем архиватор и, собственно, rsync:

sudo apt-get update
sudo apt-get install p7zip-full rsync

 

 
Код скрипта
#!/bin/bash

############# REQUIRES ################
# sudo apt-get install p7zip-full rsync
# 
# CREATE USER 'backup'@'localhost' IDENTIFIED BY 'password';
# GRANT SELECT, SHOW VIEW, RELOAD, REPLICATION CLIENT, PROCESS, EVENT, TRIGGER ON *.* TO 'backup'@'localhost';
# FLUSH PRIVILEGES;
######################################

############## SETTINGS ##############
DATE=$(date +%Y-%m-%d-%H%M%S)
TMP_PATH=/home/tmp/_backup
PREPARED_PATH=${TMP_PATH}/prepared/${DATE}
ZIP_PATH=${TMP_PATH}/zip/${DATE}
LOG_PATH=${ZIP_PATH}/backup_${DATE}.log

RSYNC_HOST=backup.com
RSYNC_USER=backup
RSYNC_PASSWORD=password
RSYNC_PATH=/backup/path

MYSQL_HOST=localhost
MYSQL_USER=backup
MYSQL_PASSWORD=backup

srcList=(
"/home/sites/"
"/etc/letsencrypt"
"/etc/nginx/"
"/etc/php5/"
"/etc/mysql/"
"/etc/exim4/"
"/etc/bind/"
"/etc/fail2ban/"
"/etc/samba/"
"/etc/network/"
"/var/spool/cron/"
"/etc/hosts"
"/etc/hostname"
"/etc/sudoers"
"/etc/rc.local"
"/etc/fstab"
)
######################################

function copy {
    mkdir -p $2
    cp --parents -r $1 $2
}

function log {
    echo "[$(date "+%Y-%m-%d %H:%M:%S")] $1" >> ${LOG_PATH}
}

rm -fr ${TMP_PATH}
mkdir -p ${PREPARED_PATH}/SQL
mkdir -p ${ZIP_PATH}

log "=================== Start backup ==================="
log "Copy files..."
    for i in ${!srcList[*]}
do
    log "Copy ${srcList[$i]}"
    copy ${srcList[$i]} ${PREPARED_PATH}
done

log "Copy DB..."
for DATABASE in $(mysql -h ${MYSQL_HOST} -u ${MYSQL_USER} -p${MYSQL_PASSWORD} -e "show databases" | awk 'NR>1'); do
    mysqldump --single-transaction --routines --host=${MYSQL_HOST} -u ${MYSQL_USER} --password=${MYSQL_PASSWORD} --result-file=${PREPARED_PATH}/SQL/${DATABASE}.sql ${DATABASE}
done

log "Compressing..."
7za -bd -mx7 -v1g a ${ZIP_PATH}/backup_${DATE}.7z ${PREPARED_PATH} >> ${LOG_PATH} 2>&1

echo ${RSYNC_PASSWORD} > ${PREPARED_PATH}/rsync.pwd
chmod 0600 ${PREPARED_PATH}/rsync.pwd

log "Transfer to backup..."
rsync -rlptDvz --password-file=${PREPARED_PATH}/rsync.pwd ${ZIP_PATH}/* rsync://${RSYNC_USER}@${RSYNC_HOST}${RSYNC_PATH}

log "Backup done."
rm -fr ${TMP_PATH}

Добавляем права на выполнение: 

chmod +x /home/user/backup.sh

 Добавим в крон на 12:00

sudo env EDITOR=nano crontab -e
0 0 * * * /home/user/backup.sh >> /var/log/backup.log 2>&1

 

Готово. Не забываем смотреть логи.

Теги: Linux, Backup

Комментарии (0)