Restore from dump linux

Linux dump резервное копирование и восстановление

Для системного администратора самой трудоёмкой, скрупулёзной и ответственной работой является (что непрерывно подтверждается практикой) не установка и наладка систем, программного обеспечения и т. д., а организация и проведение процедуры резервного копирования системы. Даже небольшие организации располагают своими, пусть и небольшими, но локальными сетями, обслуживаемыми серверами. Это позволяет значительно упростить и ускорить (при грамотном подходе, конечно) рутинную работу по специфике деятельности всей организации. Потеря информации, хранящейся даже в таких сетях и даже для небольших организаций, предприятий (или даже офиса) — в большинстве случаев наносит трудно поправимый ущерб с длительным и дорогостоящим восстановлением. Чего уж говорить о гигантских компаниях или корпорациях. В подавляющем большинстве случаев потеря информации стоит гораздо дороже, чем само оборудование.

Поэтому информацию обязательно следует защищать и самым надёжным способом для этого является резервное копирование данных. В Linux-системах на базовом уровне предусмотрена специализированная утилита dump. Она была разработана специально для осуществления резервного копирования. Наряду с ней для данной задачи можно также использовать команду tar – это будет практически также эффективно, однако dump конечно же, гораздо более удобна.

Использование команды dump

Утилита dump обладает рядом особенностей, благодаря чему многие системные администраторы используют именно её для резервного копирования данных:

  • возможность резервного копирования в инкрементном режиме, т. е. будет резервироваться только то, что было изменено с момента последнего копирования;
  • резервирование и восстановление любых типов файлов;
  • сохранение информации о владельцах файлов, режимах доступа, дат и времени их модификации;
  • резервное копирование можно выполнять сразу на несколько лент (да, да, в резервном копировании часто используются магнитные ленты в качестве носителей).

Команда dump в автоматическом режиме определит, какие файлы изменились со времени прошлого резервного копирования, формирует соответствующий список и именно эти файлы направит для копирования на внешний носитель. Надо заметить, что dump способна «понимать» исходную файловую систему на довольно низком уровне — для определения файлов для резервирования используется чтение таблицы индексных дескрипторов. Вместе с тем у утилиты dump имеются и незначительные ограничения:

  • файловые системы должны резервироваться индивидуально;
  • резервное копирование можно проводить только для локальных файловых систем.

Кстати, утилита dump также уверенно работает с именами файлов произвольной длины, т. е. ей абсолютно не важна глубина иерархии каталогов файловой системы.

Создание резервных копий

Команда dump сканирует файл /etc/dumpdates на предмет того, как давно создавался последний архив. С помощью ключа -u можно заставить dump самостоятельно после завершения резервного копирования обновлять вышеуказанный файл, занося в него информацию о дате, имени файловой системы и уровне архива. Без использования ключа -u (если он вообще ни разу не использовался) все архивы будут иметь нулевой уровень.

Для выбора внешнего устройства для хранения резервной копии существует ключ -f, иначе будет использоваться устройство по-умолчанию, как правило, это ленточный носитель.

Итак, для создания резервной копии утилитой dump нужно дать следующую команду:

Или для варианта с ленточным носителем:

Здесь с ключом -u задаётся нулевой уровень архива (0), а ключом -f – устройство /dev/sdd1 для сохранения резервной копии файловой системы /home. Удалённый носитель (во втором примере ленточный носитель nst0) задаётся в формате имя_компьютера:устройство.

Восстановление файлов из резервных архивов

Чтобы восстановить отдельные файлы из резервных копий, следует воспользоваться командой restore. Эта команда обладает большим набором опций для выполнения. Среди которых одной из самых важных является -i – этот ключ позволяет работать с восстановлением в интерактивном режиме. Также имеются опции -r – для восстановления файловой системы целиком. И -x – для автоматического восстановления заранее указанных файлов.

В интерактивном режиме (ключ -i) команда restore сначала читает состав содержимого архива, после чего даёт возможность пользователю перемещаться по этому содержимому как по дереву каталогов в файловой системе, используя команды cd, ls и pwd. Чтобы восстановить требуемые файлы, нужно сначала добавить их в список восстановления командой add. Для восстановления выбранных (добавленных в список восстановления) файлов нужно выполнить команду extract. Также можно удалять файлы из списка восстановления — командой delete. Пример:

В приведённом примере показан наиболее общий и «суровый» случай, когда нужно восстановить архив с удалённого ленточного носителя по SSH. Здесь также используется перемотка ленты командой mt для перехода к нужному архиву — это тот случай, когда на одной ленте их несколько. В качестве параметров команде mt передаются: удаленное устройство и параметры перемотки — fsf 3, т. е. лента должна быть перемотана вперёд на 3 файла. Если архив умещается на одной ленте, то на запрос «Specify next volume #:» нужно ввести 1. Также нужно определить, должен ли текущий каталог соответствовать корневому каталогу текущей ленты и если восстанавливается не вся файловая система целиком, то можно ответить «n» — нет. Восстановление производится в текущий каталог /var/restore.

Читайте также:  Sha1 windows 10 enterprise

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

restore(8) — Linux man page

Synopsis

Description

Exactly one of the following flags is required: -C This mode allows comparison of files from a dump. Restore reads the backup and compares its contents with files present on the disk. It first changes its working directory to the root of the filesystem that was dumped and compares the tape with the files in its new current directory. See also the -L flag described below. -i This mode allows interactive restoration of files from a dump. After reading in the directory information from the dump, restore provides a shell like interface that allows the user to move around the directory tree selecting files to be extracted. The available commands are given below; for those commands that require an argument, the default is the current directory. add [arg] The current directory or specified argument is added to the list of files to be extracted. If a directory is specified, then it and all its descendents are added to the extraction list (unless the -h flag is specified on the command line). Files that are on the extraction list are prepended with a ‘*’ when they are listed by ls. cd arg Change the current working directory to the specified argument. delete [arg] The current directory or specified argument is deleted from the list of files to be extracted. If a directory is specified, then it and all its descendents are deleted from the extraction list (unless the -h flag is specified on the command line). The most expedient way to extract most of the files from a directory is to add the directory to the extraction list and then delete those files that are not needed. extract All files on the extraction list are extracted from the dump. Restore will ask which volume the user wishes to mount. The fastest way to extract a f ew files is to start with the last volume and work towards the first volume. help List a summary of the available commands. ls [arg] List the current or specified directory. Entries that are directories are appended with a ‘/’. Entries that have been marked for extraction are prepended with a ‘*’. If the verbose flag is set, the inode number of each entry is also listed. pwd Print the full pathname of the current working directory. quit Restore immediately exits, even if the extraction list is not empty. setmodes All directories that have been added to the extraction list have their owner, modes, and times set; nothing is extracted from the dump. This is useful for cleaning up after a restore has been prematurely aborted. verbose The sense of the -v flag is toggled. When set, the verbose flag causes the ls command to list the inode numbers of all entries. It also causes restore to print out information about each file as it is extracted. -P file Restore creates a new Quick File Access file file from an existing dump file without restoring its contents. -R Restore requests a particular tape of a multi-volume set on which to restart a full restore (see the -r flag below). This is useful if the restore has been interrupted. -r Restore (rebuild) a file system. The target file system should be made pristine with mke2fs(8), mounted, and the user cd‘d into the pristine file system before starting the restoration of the initial level 0 backup. If the level 0 restores successfully, the -r flag may be used to restore any necessary incremental backups on top of the level 0. The -r flag precludes an interactive file extraction and can be detrimental to one’s health (not to mention the disk) if not used carefully. An example: mke2fs /dev/sda1 mount /dev/sda1 /mnt cd /mnt restore rf /dev/st0 Note that restore leaves a file restoresymtable in the root directory to pass information between incremental restore passes. This file should be removed when the last incremental has been restored. Restore, in conjunction with mke2fs(8) and dump(8), may be used to modify file system parameters such as size or block size. -t The names of the specified files are listed if they occur on the backup. If no file argument is given, the root directory is listed, which results in the entire content of the backup being listed, unless the -h flag has been specified. Note that the -t flag replaces the function of the old dumpdir(8) program. See also the -X option below. -x The named files are read from the given media. If a named file matches a directory whose contents are on the backup and the -h flag is not specified, the directory is recursively extracted. The owner, modification time, and mode are restored (if possible). If no file argument is given, the root directory is extracted, which results in the entire content of the backup being extracted, unless the -h flag has been specified. See also the -X option below.

Читайте также:  Что такое кластер windows 2012

Options

002 etc. -N The -N flag causes restore to perform a full execution as requested by one of -i, -R, -r, t or x command without actually writing any file on disk. -o The -o flag causes restore to automatically restore the current directory permissions without asking the operator whether to do so in one of -i or -x modes. -Qfile Use the file file in order to read tape position as stored using the dump Quick File Access mode, in one of -i, -x or -t mode. It is recommended to set up the st driver to return logical tape positions rather than physical before calling dump/restore with parameter -Q. Since not all tape devices support physical tape positions those tape devices return an error during dump/restore when the st driver is set to the default physical setting. Please see the st(4) man page, option MTSETDRVBUFFER , or the mt(1) man page, on how to set the driver to return logical tape positions. Before calling restore with parameter -Q, always make sure the st driver is set to return the same type of tape position used during the call to dump. Otherwise restore may be confused. This option can be used when restoring from local or remote tapes (see above) or from local or remote files. -s fileno Read from the specified fileno on a multi-file tape. File numbering starts at 1. -T directory The -T flag allows the user to specify a directory to use for the storage of temporary files. The default value is /tmp. This flag is most useful when restoring files after having booted from a floppy. There might be little or no space on the floppy filesystem, but another source of space might exist. -u When creating certain types of files, restore may generate a warning diagnostic if they already exist in the target directory. To prevent this, the -u (unlink) flag causes restore to remove old entries before attempting to create new ones. -v Normally restore does its work silently. The -v (verbose) flag causes it to type the name of each file it treats preceded by its file type. -V Enables reading multi-volume non-tape mediums like CDROMs. -X filelist Read list of files to be listed or extracted from the text file filelist in addition to those specified on the command line. This can be used in conjunction with the -t or -x commands. The file filelist should contain file names separated by newlines. filelist may be an ordinary file or (the standard input). -y Do not ask the user whether to abort the restore in the event of an error. Always try to skip over the bad block(s) and continue.

(The 4.3BSD option syntax is implemented for backward compatibility but is not documented here.)

Diagnostics

If a backup was made using more than one tape volume, restore will notify the user when it is time to mount the next volume. If the -x or -i flag has been specified, restore will also ask which volume the user wishes to mount. The fastest way to extract a few files is to start with the last volume, and work towards the first volume.

Читайте также:  Ratiborus windows 10 digital activation program

There are numerous consistency checks that can be listed by restore. Most checks are self-explanatory or can ‘never happen’. Common errors are given below: Converting to new file system format A dump tape created from the old file system has been loaded. It is automatically converted to the new file system format. : not found on tape The specified file name was listed in the tape directory, but was not found on the tape. This is caused by tape read errors while looking for the file, and from using a dump tape created on an active file system. expected next file , got A file that was not listed in the directory showed up. This can occur when using a dump created on an active file system. Incremental dump too low When doing an incremental restore, a dump that was written before the previous incremental dump, or that has too low an incremental level has been loaded. Incremental dump too high When doing an incremental restore, a dump that does not begin its coverage where the previous incremental dump left off, or that has too high an incremental level has been loaded. Tape read error while restoring Tape read error while skipping over inode Tape read error while trying to resynchronize A tape (or other media) read error has occurred. If a file name is specified, its contents are probably partially wrong. If an inode is being skipped or the tape is trying to resynchronize, no extracted files have been corrupted, though files may not be found on the tape. resync restore, skipped blocks After a dump read error, restore may have to resynchronize itself. This message lists the number of blocks that were skipped over.

Exit Status

When doing a comparison of files from a dump, an exit code of 2 indicates that some files were modified or deleted since the dump was made.

Environment

Files

See Also

A level 0 dump must be done after a full restore. Because restore runs in user code, it has no control over inode allocation; thus a full dump must be done to get a new set of directories reflecting the new inode numbering, even though the content of the files is unchanged.

The temporary files /tmp/rstdir* and /tmp/rstmode* are generated with a unique name based on the date of the dump and the process ID (see mktemp(3)), except when -r or -R is used. Because -R allows you to restart a -r operation that may have been interrupted, the temporary files should be the same across different processes. In all other cases, the files are unique because it is possible to have two different dumps started at the same time, and separate operations shouldn’t conflict with each other.

To do a network restore, you have to run restore as root or use a remote shell replacement (see RSH variable). This is due to the previous security history of dump and restore. ( restore is written to be setuid root, but we are not certain all bugs are gone from the code — run setuid at your own risk.)

At the end of restores in -i or -x modes (unless -o option is in use), restore will ask the operator whether to set the permissions on the current directory. If the operator confirms this action, the permissions on the directory from where restore was launched will be replaced by the permissions on the dumped root inode. Although this behaviour is not really a bug, it has proven itself to be confusing for many users, so it is recommended to answer ‘no’, unless you’re performing a full restore and you do want to restore the permissions on ‘/’.

It should be underlined that because it runs in user code, restore , when run with the -C option, sees the files as the kernel presents them, whereas dump sees all the files on a given filesystem. In particular, this can cause some confusion when comparing a dumped filesystem a part of which is hidden by a filesystem mounted on top of it.

Author

Starting with 0.4b5, the new maintainer is Stelian Pop .

Источник

Оцените статью