Сценарии Shell Сравнение версий

Различия

Здесь показаны различия между двумя версиями данной страницы.

Ссылка на это сравнение

Предыдущая версия справа и слева Предыдущая версия
Следующая версия
Предыдущая версия
wiki:руководство_по_ubuntu_server:резервное_копирование:shell_scripts [2012/09/20 19:28]
[Сценарии Shell]
wiki:руководство_по_ubuntu_server:резервное_копирование:shell_scripts [2012/09/20 21:43] (текущий)
[Ссылки]
Строка 14: Строка 14:
 ====Простой Shell сценарий==== ====Простой Shell сценарий====
  
-The following ​shell script uses tar to create an archive file on a remotely mounted NFS file systemThe archive filename is determined using additional command line utilities. +Следующий ​shell сценарий использует **tar** для создания архивного файла на удаленно смонтированной файловой системеИмя архива определяется с помощью дополнительных утилит командной строки.
 <​code>​ <​code>​
 #!/bin/sh #!/bin/sh
Строка 52: Строка 51:
 </​code>​ </​code>​
  
-    ​$backup_files: ​a variable listing which directories you would like to backupThe list should be customized to fit your needs.+  ~~ **$backup_files**переменная для перечисления какие каталоги вы желаете сохранятьСписок может быть изменен под ваши требования. 
 +  ~~ **$day**: переменная,​ содержащая день недели. Она используется для создания архивных файлов на каждый день недели,​ обеспечивая историю резервного копирования на семь дней. Существуют иные способы получения такого результата,​ включая использование утилиты **date**. 
 +  ~~ **$hostname**:​ переменная,​ содержащая короткое сетевое имя системы. Использование сетевого имени в имени архива позволяет вам помещать ежедневные архивы от разных систем в один каталог. 
 +  ~~ **$archive_file**:​ полное имя архива. 
 +  ~~ **$dest**: место расположения архивного файла. Каталог должен быть создан и в данном случае смонтирован до выполнения сценария резервного копирования. Смотрите раздел [[wiki:​руководство_по_ubuntu_server:​файловые_сервера:​nfs|Сетевая файловая система (NFS)]] для уточнения деталей использования NFS. 
 +  ~~ **status messages**: необязательные сообщения,​ выводимые в консоль с использованием утилиты **echo**. 
 +  ~~ **tar czf $dest/​$archive_file $backup_files**:​ команда **tar**, используемая для создания архивного файла. 
 +    ~~ **c**: создание архива. 
 +    ~~ **z**: пропускание архива через утилиту сжатия **gzip**. 
 +    ~~ **f**: вывод в архивный файл. В противном случае **tar** будет посылать результат в STDOUT. 
 +  ~~ **ls -lh $dest**: необязательный оператор,​ выводящий **//-l//** длинный вариант списка в **//-h//** читаемом виде целевого каталога. Это удобно для быстрой проверки размера архивного файла. Эта проверка не заменяет тестирования целостности архивного файла.
  
-    $day: a variable holding the day of the week (MondayTuesdayWednesday, etc)This is used to create an archive file for each day of the weekgiving a backup history of seven days. There are other ways to accomplish this including using the date utility.+Это простой пример сценария резервного копированияоднако есть много опцийкоторые можно включить в такой сценарийСмотрите [[#​ссылки|Ссылки]] для указаний на ресурсыпредоставляющие более глубокое описание shell сценариев.
  
-    $hostname: variable containing the short hostname of the system. Using the hostname in the archive filename gives you the option of placing daily archive files from multiple systems in the same directory. 
  
-    $archive_file:​ the full archive filename.+====Выполнение сценария====
  
-    $dest: destination of the archive file. The directory needs to be created and in this case mounted before executing the backup script. See Network File System (NFS) for details of using NFS. 
- 
-    status messages: optional messages printed to the console using the echo utility. 
- 
-    tar czf $dest/​$archive_file $backup_files:​ the tar command used to create the archive file. 
- 
-        c: creates an archive. 
- 
-        z: filter the archive through the gzip utility compressing the archive. 
- 
-        f: output to an archive file. Otherwise the tar output will be sent to STDOUT. 
- 
-    ls -lh $dest: optional statement prints a -l long listing in -h human readable format of the destination directory. This is useful for a quick file size check of the archive file. This check should not replace testing the archive file. 
- 
-This is a simple example of a backup shell script; however there are many options that can be included in such a script. See References for links to resources providing more in-depth shell scripting information. 
- 
-====Выполнение сценария==== 
 ===Выполнение сценария из терминала=== ===Выполнение сценария из терминала===
  
-The simplest way of executing the above backup script is to copy and paste the contents into a file. backup.sh ​for exampleThen 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 executionThe 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 onbetween 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 crontabThis 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 archiveThe archive can be tested by listing the files it containsbut the best test is to restore a file from the archive.+Как только архив создан,​ важно проверить архивАрхив может быть проверен выводом списка файлов,​ которые в нем находятсяно лучшей проверкой будет восстановление файлов из архива.
  
-    To see a listing of the archive contentsFrom a terminal prompt type:+ 1Чтобы посмотреть содержимое архива,​ наберите в терминале: 
 +<​code>​tar -tzvf /​mnt/​backup/​host-Monday.tgz</​code>​
  
-    ​tar -tzvf /​mnt/​backup/​host-Monday.tgz+ 2. Чтобы восстановить файлы из архива в другой каталог введите:​ 
 +<​code>​tar -xzvf /​mnt/​backup/​host-Monday.tgz ​-C /tmp etc/​hosts</​code>​ 
 +Параметр **//-C//** команды **//tar//** перенаправляет извлекаемые файлы в указанный каталог. Приведенный пример извлечет файл /etc/hosts в /​tmp/​etc/​hosts. **tar** создает заново структуру каталогов для извлекаемых файлов.
  
-    To restore a file from the archive to a different directory enter:+Также обратите внимание на отсутствие лидирующего %%"/"​%% в пути извлекаемого файла.
  
-    tar -xzvf /​mnt/​backup/​host-Monday.tgz -C /tmp etc/hosts + 3Для восстановления всех файлов архива введите следующее
- +<​code>​ 
-    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. +cd / 
- +sudo tar -xzvf /​mnt/​backup/​host-Monday.tgz 
-    Also, notice the leading "/"​ is left off the path of the file to restore. +</​code>​ 
- +<​note>​Это перепишет все файлы, находящиеся в файловой системе.</​note>​
-    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: +
- +
-        cpio: used to copy files to and from archives. +
- +
-        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.+
  
-        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]]:​ гибкая утилита,​ используемая для копирования измененных частей файлов (инкрементное копирование).
  
 ---- ----