Решение
Этот скрипт может быть использовать и в Unix-системах, и в Windows с использованием Cygwin.
Также его можно использовать, если нет доступа к SSH (shared-хостинг).
Что делает скрипт?
Полная резервная копия Drupal включает дамп базы данных и файловой системы.
Скрипт создания резервной копии делает дамп файловой системы, используя команду tar, и дамп базы данных, используя утилиту mysqldump. Эти два дампа объединяются в один tar-файл. Tar-файл сжат и его имя файла включает дату создания резервной копии.
Использование
Перед использованием скрипта укажите резервную копию чего нужно делать в блоке "Configuration".
Имя файла по умолчанию состоит из значения переменной tarnamebase с добавлением даты.
Значение по умолчанию переменной tarnamebase равно fullsitebackup. Например: fullsitebackup-2006-04-14.tgz. Это может быть переопределено указанием имени файла в параметре P1.
Запуск скрипта
или
Вам предложат указать пароль к базе данных.
Файл резервной копии размещается в папке из которой вызван скрипт.
Мультисайтинг
Если несколько сайтов размещаются в одной системе (мультисайтинг), создайте отдельный скрипт для каждого и переименуйте их так, чтобы можно было узнать к какому сайту они относятся.
Для сайта mysite1 - mysite1fullbackup.sh.
Нужно также настроить переменную tarnamebase для более полного описания сайта.
Usage notes and warnings:
- This script backs up every file and directory in the Drupal root directory. If you have a hosted site with subdomain websites contained in subdirectories a backup of the main website directory will include the subdomain websites. For backups this will only bloat your backup file. For restores this could be disastrous, since you would restoring the file systems for ALL of the website. If you have this kind of configuration you must customize the tar command to make a selective backup.
- This script does not understand Drupal multisite configurations
- This script does not lock out users while the backup is in progress
- Read access is required on all files and directories (this is sometimes a problem in hosted configurations)
- The mysqldump utility uses the --add-drop-table option so that a restore automatically replaces tables. You may wish to modify this to add an element of safety to your restore process. (e.g., tables must be manually dropped, script will not replace)
- Commands may need to be modified for your operating system (e.g., The default tar command in Solaris does not support compression)
- Because the backup is done in stages enough temporary space must be available to build the backup files
Код скрипта
Скопируйте текст в файл и назовите его fullsitebackup.sh.
Убедитесь, что специальные символы, типа апостроф ("`") и ковычки сохранены корректно.
#
# fullsitebackup.sh V1.1
#
# Full backup of website files and database content.
#
# A number of variables defining file location and database connection
# information must be set before this script will run.
# Files are tar'ed from the root directory of the website. All files are
# saved. The MySQL database tables are dumped without a database name and
# and with the option to drop and recreate the tables.
#
# ----------------------
# March 2007 Updates
# - Updated script to resolve minor path bug
# - Added mysql password variable (caution - this script file is now a security risk - protect it)
# - Generates temp log file
# - Updated backup and restore scripts have been tested on Ubunutu Edgy server w/Drupal 5.1
#
# - Enjoy! BristolGuy
#-----------------------
#
## Parameters:
# tar_file_name (optional)
#
#
# Configuration
#
# Database connection information
dbname="drupal" # (e.g.: dbname=drupaldb)
dbhost="localhost"
dbuser="" # (e.g.: dbuser=drupaluser)
dbpw="" # (e.g.: dbuser password)
# Website Files
webrootdir="/var/www/drupal" # (e.g.: webrootdir=/home/user/public_html)
#
# Variables
#
# Default TAR Output File Base Name
tarnamebase=sitebackup-
datestamp=`date +'%m-%d-%Y'`
# Execution directory (script start point)
startdir=`pwd`
logfile=$startdir"/fullsite.log" # file path and name of log file to use
# Temporary Directory
tempdir=$datestamp
#
# Input Parameter Check
#
if test "$1" = ""
then
tarname=$tarnamebase$datestamp.tgz
else
tarname=$1
fi
#
# Begin logging
#
echo "Beginning drupal site backup using fullsitebackup.sh ..." > $logfile
#
# Create temporary working directory
#
echo " Creating temp working dir ..." >> $logfile
#mkdir $tempdir
/bin/mkdir $startdir/$tempdir
#
# TAR website files
#
echo " TARing website files into $webrootdir ..." >> $logfile
cd $webrootdir
tar cf $startdir/$tempdir/filecontent.tar .
#
# sqldump database information
#
echo " Dumping drupal database, using ..." >> $logfile
echo " user:$dbuser; database:$dbname host:$dbhost " >> $logfile
cd $startdir/$tempdir
mysqldump --user=$dbuser --host=$dbhost --password=$dbpw --add-drop-table $dbname > dbcontent.sql
#
# Create final backup file
#
echo " Creating final compressed (tgz) TAR file: $tarname ..." >> $logfile
tar czf $startdir/$tarname filecontent.tar dbcontent.sql
#
# Cleanup
#
echo " Removing temp dir $tempdir ..." >> $logfile
cd $startdir
rm -r $tempdir
#
# Exit banner
#
endtime=`date`
echo "Backup completed $endtime, TAR file at $tarname. " >> $logfile
Использование скрипта на shared-хостинге, где нет SSH
Нужно создать php-скрипт и выполнить через браузер:
Ротация файлов резервных копий
По умолчанияю создаются файлы вида drupalcookbook-25-08-2008.tgz и они могут быстро исчерпать доступное место на диске. Один из самых простых способов решить эту проблему - задать переменную datestamp с скрипте:
datestamp=`date +'%u'`
Тогда файлы будут иметь вид:
drupalcookbook-1.tgz - для понедельника, drupalcookbook-3.tgz - для среды и т.д.
Через неделю эти файлы будут перезаписаны более свежей версией бекапа.
Использованные материалы
Backup and restore using bash shell scripts - описание скриптов
fullsitebackup.sh - идея использования скрипта на сервере без SSH.
Updated fullsitebackup.sh - сам скрипт
Полезные ссылки
Обработать
Drupal multisite, clean URLs and lighttpd
Rotate FTP Backup Using a Shell Script










