Различия
Здесь показаны различия между двумя версиями данной страницы.
Предыдущая версия справа и слева Предыдущая версия Следующая версия | Предыдущая версия | ||
wiki:руководство_по_ubuntu_server:резервное_копирование:shell_scripts [2012/09/20 20:36] [Простой Shell сценарий] |
wiki:руководство_по_ubuntu_server:резервное_копирование:shell_scripts [2012/09/20 21:43] (текущий) [Ссылки] |
||
---|---|---|---|
Строка 67: | Строка 67: | ||
====Выполнение сценария==== | ====Выполнение сценария==== | ||
+ | |||
===Выполнение сценария из терминала=== | ===Выполнение сценария из терминала=== | ||
- | The simplest way of executing the above backup script is to copy and paste the contents into a file. backup.sh for example. Then from a terminal prompt: | + | Простейший способ выполнить приведенный выше сценарий - это скопировать его содержимое в файл. Например, backup.sh. Затем ввести в терминале: |
+ | <code>sudo bash backup.sh</code> | ||
- | sudo bash backup.sh | + | Это прекрасный способ проверить сценарий, чтобы убедиться что все работает как задумывалось. |
- | + | ||
- | This is a great way to test the script to make sure everything works as expected. | + | |
===Выполнение с помощью cron=== | ===Выполнение с помощью cron=== | ||
- | The cron utility can be used to automate the script execution. The cron daemon allows the execution of scripts, or commands, at a specified time and date. | + | Утилита **cron** может быть использована для автоматизации выполнения сценария. Сервис **cron** позволяет выполнять сценарии или команды в определенное время. |
- | cron is configured through entries in a crontab file. crontab files are separated into fields: | + | **cron** настраивается через записи в файле crontab. Файлы crontab разделяются на поля: |
+ | <code># m h dom mon dow command</code> | ||
- | # m h dom mon dow command | + | -- **m**: минуты запуска команды, от 0 до 59. |
+ | -- **h**: час запуска команды, от 0 до 23. | ||
+ | -- **dom**: день месяца для выполнения команды. | ||
+ | -- **mon**: месяц даты выполнения команды. | ||
+ | -- **dow**: день недели для выполнения команды, от 0 до 7. Воскресенье может быть обозначено как 0 так и 7, оба значения допустимы. | ||
+ | -- **command**: выполняемая команда. | ||
- | m: minute the command executes on, between 0 and 59. | + | Для добавления или изменения записей в файле crontab используется команда **//crontab -e//**. Кроме того, содержимое файла crontab можно просмотреть с помощью команды **//crontab -l//**. |
- | h: hour the command executes on, between 0 and 23. | + | Для выполнения сценария backup.sh, приведенного выше с помощью cron, введите следующее в терминале: |
- | + | <code>sudo crontab -e</code> | |
- | dom: day of month the command executes on. | + | <note>Использование **sudo** для выполнения команды **crontab -e** изменяет файл crontab пользователя root. Это требуется для резервного копирования каталогов, доступ к которым разрешен только root.</note> |
- | + | ||
- | mon: the month the command executes on, between 1 and 12. | + | |
- | + | ||
- | dow: the day of the week the command executes on, between 0 and 7. Sunday may be specified by using 0 or 7, both values are valid. | + | |
- | + | ||
- | command: the command to execute. | + | |
- | + | ||
- | To add or change entries in a crontab file the crontab -e command should be used. Also, the contents of a crontab file can be viewed using the crontab -l command. | + | |
- | + | ||
- | To execute the backup.sh script listed above using cron. Enter the following from a terminal prompt: | + | |
- | + | ||
- | sudo crontab -e | + | |
- | + | ||
- | Using sudo with the crontab -e command edits the root user's crontab. This is necessary if you are backing up directories only the root user has access to. | + | |
- | + | ||
- | Add the following entry to the crontab file: | + | |
+ | Добавьте следующую запись в файл crontab: | ||
+ | <code> | ||
# m h dom mon dow command | # m h dom mon dow command | ||
0 0 * * * bash /usr/local/bin/backup.sh | 0 0 * * * bash /usr/local/bin/backup.sh | ||
+ | </code> | ||
+ | Сценарий backup.sh будет теперь выполняться каждый день в полночь. | ||
- | The backup.sh script will now be executed every day at 12:00 am. | + | <note>Сценарий backup.sh требуется скопировать в каталог /usr/local/bin/ чтобы данная запись выполнялась правильно. Сценарий можно разместить где угодно на файловой системе, просто соответственно измените путь к сценарию в crontab.</note> |
- | The backup.sh script will need to be copied to the /usr/local/bin/ directory in order for this entry to execute properly. The script can reside anywhere on the file system, simply change the script path appropriately. | + | Для более глубокого изучения опций crontab смотрите секцию [[#ссылки|Ссылки]]. |
- | + | ||
- | For more in-depth crontab options see References. | + | |
====Восстановление из архива==== | ====Восстановление из архива==== | ||
- | Once an archive has been created it is important to test the archive. The archive can be tested by listing the files it contains, but the best test is to restore a file from the archive. | + | Как только архив создан, важно проверить архив. Архив может быть проверен выводом списка файлов, которые в нем находятся, но лучшей проверкой будет восстановление файлов из архива. |
- | + | ||
- | To see a listing of the archive contents. From a terminal prompt type: | + | |
- | + | ||
- | tar -tzvf /mnt/backup/host-Monday.tgz | + | |
- | + | ||
- | To restore a file from the archive to a different directory enter: | + | |
- | + | ||
- | tar -xzvf /mnt/backup/host-Monday.tgz -C /tmp etc/hosts | + | |
- | + | ||
- | The -C option to tar redirects the extracted files to the specified directory. The above example will extract the /etc/hosts file to /tmp/etc/hosts. tar recreates the directory structure that it contains. | + | |
- | + | ||
- | Also, notice the leading "/" is left off the path of the file to restore. | + | |
- | + | ||
- | To restore all files in the archive enter the following: | + | |
- | + | ||
- | cd / | + | |
- | sudo tar -xzvf /mnt/backup/host-Monday.tgz | + | |
- | + | ||
- | This will overwrite the files currently on the file system. | + | |
- | + | ||
- | ====Сылки==== | + | |
- | + | ||
- | For more information on shell scripting see the Advanced Bash-Scripting Guide | + | |
- | + | ||
- | The book Teach Yourself Shell Programming in 24 Hours is available online and a great resource for shell scripting. | + | |
- | + | ||
- | The CronHowto Wiki Page contains details on advanced cron options. | + | |
- | + | ||
- | See the GNU tar Manual for more tar options. | + | |
- | + | ||
- | The Wikipedia Backup Rotation Scheme article contains information on other backup rotation schemes. | + | |
- | The shell script uses tar to create the archive, but there many other command line utilities that can be used. For example: | + | 1. Чтобы посмотреть содержимое архива, наберите в терминале: |
+ | <code>tar -tzvf /mnt/backup/host-Monday.tgz</code> | ||
- | cpio: used to copy files to and from archives. | + | 2. Чтобы восстановить файлы из архива в другой каталог введите: |
+ | <code>tar -xzvf /mnt/backup/host-Monday.tgz -C /tmp etc/hosts</code> | ||
+ | Параметр **//-C//** команды **//tar//** перенаправляет извлекаемые файлы в указанный каталог. Приведенный пример извлечет файл /etc/hosts в /tmp/etc/hosts. **tar** создает заново структуру каталогов для извлекаемых файлов. | ||
- | dd: part of the coreutils package. A low level utility that can copy data from one format to another. | + | Также обратите внимание на отсутствие лидирующего %%"/"%% в пути извлекаемого файла. |
- | rsnapshot: a file system snapshot utility used to create copies of an entire file system. | + | 3. Для восстановления всех файлов архива введите следующее: |
+ | <code> | ||
+ | cd / | ||
+ | sudo tar -xzvf /mnt/backup/host-Monday.tgz | ||
+ | </code> | ||
+ | <note>Это перепишет все файлы, находящиеся в файловой системе.</note> | ||
- | rsync: a flexible utility used to create incremental copies of files. | + | ====Ссылки==== |
+ | ~~ Для дополнительной информации по shell сценариям смотрите руководство [[http://tldp.org/LDP/abs/html/|Advanced Bash-Scripting Guide]]. | ||
+ | ~~ Книга [[http://safari.samspublishing.com/0672323583|Teach Yourself Shell Programming in 24 Hours]] доступна в сети и является замечательным ресурсом для создания shell сценариев. | ||
+ | ~~ Страница [[https://help.ubuntu.com/community/CronHowto|CronHowto Wiki]] содержит подробности по дополнительным опциям **cron**. | ||
+ | ~~ Смотрите руководство [[http://www.gnu.org/software/tar/manual/index.html|GNU tar Manual]] для дополнительных параметров **tar**. | ||
+ | ~~ Статья [[http://en.wikipedia.org/wiki/Backup_rotation_scheme|Wikipedia Backup Rotation Scheme]] содержит информацию по другим схемам ротации архивов. | ||
+ | ~~ Shell сценарий использует **tar** для создания архива, но существует много других утилит, которые можно использовать. Например: | ||
+ | ~~ [[http://www.gnu.org/software/cpio/|cpio]]: используется для копирования файлов в и из архива. | ||
+ | ~~ [[http://www.gnu.org/software/coreutils/|dd]]: часть пакета **coreutils**. Утилита нижнего уровня, которая может копировать данные из одного формата в другой. | ||
+ | ~~ [[http://www.rsnapshot.org/|rsnapshot]]: утилита получения снимка файловой системы, используемая для получения копий всей файловой системы. | ||
+ | ~~ [[http://www.samba.org/ftp/rsync/rsync.html|rsync]]: гибкая утилита, используемая для копирования измененных частей файлов (инкрементное копирование). | ||
---- | ---- |