Disk recovery in linux

Disk recovery in linux

Наши партнеры

Библиотека сайта rus-linux.net

2. ddrescue

Хотя ddrescue не является инструментом восстановления данных, он должен стать вашим первым шагом на пути к извлечению ваших файлов. Ddrescue создает образ вашего поврежденного диска или раздела, чтобы вы могли проанализировать копию вашего сломанного диска.

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

Здесь вы видите некоторые результаты ddrescue в действии. В первой команде он копирует весь диск в образ с именем «backup.img». Вторая команда затем копирует в тот же образ только плохие блоки, проходя каждый раз по этим блокам, чтобы попытаться их прочитать.

Когда вы запускаете эти команды, всегда используйте файл журнала. Резервное копирование может занять несколько часов или дней, и без лог-файла любые прерывания заставят вас начать процесс заново с самого начала.

Когда этот процесс завершен, вы можете смонтировать скопированный образ и использовать приведенные далее утилиты для извлечения из него файлов. Дальнейшее использование других инструментов восстановления Linux из этой статьи позволит получить данные из того же «backup.img», созданного здесь.

3. Foremost

Foremost использует структуры данных общих типов файлов для извлечения данных. Вы можете просканировать весь образ диска для всех его файлов или указать определенные типы файлов, которые вам наиболее интересны.

Здесь вы можете увидеть вывод Foremost в подробном режиме (опция -v). Опция -t ищет типы файлов jpg, а опции -i и -o отмечают соответствующий входной файл и выходной каталоги.

Вы можете видеть, что Foremost анализирует образ, созданный на предыдущем шаге; этот образ содержит несколько JPEG-файлов. Foremost смог найти десять таких файлов, и когда он закончил сканирование образа, он скопировал эти десять файлов в указанную выходную папку.

4. scalpel

Scalpel , изначально основанный на Foremost, стремится быть экономным в своей работе. Он использует многопоточность и асинхронный ввод/вывод для эффективного поиска.

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

На этом снимке экрана вы можете увидеть окончательный результат анализа Scalpel для «backup.img». Базовая команда (приведенная в нижней части снимка экрана) требует только выходной каталог и образ для анализа.

5. PhotoRec

PhotoRec отстает от своих конкурентов, сосредоточившись на восстановлении фотографий, видео и текстовых документов. Он также работает как интерактивная утилита внутри консоли.

В команде PhotoRec должен быть указан желаемый образ (наш backup.img) и выходная папка. Затем PhotoRec помещает пользователя в графическое окружение. Скриншот здесь показывает размер образа. На следующих экранах запрашивается тип раздела диска и хотите ли вы искать файлы по всему образу.

6. grep

Наконец, мы подошли к grep . Он может показаться не самым простым вариантом восстановления, но grep может находить удаленные или потерянные текстовые файлы путем поиска строк, присутствующих на блочном устройстве или образе диска.

В образе backup.img существует файл с именем «myfile». Он содержит только одну строку текста: «This is the file I will try to recover.»

Grep использует эту строку в качестве отправной точки для восстановления файлов. Помимо нескольких других параметров, вы можете видеть, что в этом примере он выводит найденную строку в новый двоичный файл с именем «foundtext».

Также, вы можете изменить параметр -C, который печатает дополнительный контекст, окружающий строку в исходной команде. В этом примере команда указывает grep найти одну строку текста до и одну после указанной строки.

Начиная с -C 200, grep найдет 200 строк как до, так и после строки. Такой охват здесь не нужен, но он может быть важен для больших текстовых файлов с сотнями строк. Конечно, вам нужно знать содержимое ваших файлов, чтобы у grep была отправная точка для начала поиска.

Grep создаст в качестве вывода двоичный файл. Тем не менее, некоторые части будут удобочитаемыми, например желаемая строка текста этого примера в нижней части этого снимка экрана. Ваша задача — вручную выбрать нужные данные. Конечно, это тяжелая работа, но она лучше альтернативы отсутствия файлов.

Читайте также:  Замена во всей базе данных wordpress

Заключение

Итак, сначала скопируйте ваш диск или раздел с помощью ddrescue, а затем работайте с этой копией с помощью любых инструментов восстановления Linux, которые вам нужны. Не бойтесь попробовать более одного инструмента, особенно если ваш первый выбор не нашел данных, которые вы хотели найти. Будьте терпеливыми. Если вам повезет, вы вернете свои драгоценные файлы еще до того, как узнаете об этом.

Источник

File recovery

This article lists data recovery and undeletion options for Linux.

Contents

Special notes

Before you start

This article or section needs expansion.

This page is mostly intended to be used for educational purposes. If you have accidentally deleted or otherwise damaged your valuable and irreplaceable data and have no previous experience with data recovery, turn off your computer immediately (Just press and hold the off button or pull the plug; do not use the system shutdown function) and seek professional help.

Failing drives

In the area of data recovery, it is best to work on images of disks rather than physical disks themselves. Generally, a failing drive’s condition worsens over time. The goal ought to be to first rescue as much data as possible as early as possible in the failure of the disk and to then abandon the disk. The ddrescue and dd_rescue utilities, unlike dd , will repeatedly try to recover from errors and will read the drive front to back, then back to front, attempting to salvage data. They keep log files so that recovery can be paused and resumed without losing progress.

The image files created from a utility like ddrescue can then be mounted like a physical device and can be worked on safely. Always make a copy of the original image so that you can revert if things go sour!

The factual accuracy of this article or section is disputed.

A tried and true method of improving failing drive reads is to keep the drive cold. A bit of time in the freezer is appropriate, but be careful to avoid bringing the drive from cold to warm too quickly, as condensation will form. Keeping the drive in the freezer with cables connected to the recovering PC works great.

Do not attempt a filesystem check on a failing drive, as this will likely make the problem worse. Mount it read-only.

Backup flash media/small partitions

As an alternative to working with a ‘live’ partition (mounted or not), it is often preferable to work with an image, provided that the filesystem in question is not too large and that you have sufficient free HDD space to accommodate the image file. For example, flash memory devices like thumb drives, digital cameras, portable music players, cellular phones, etc. are likely to be small enough to image in many cases.

Be sure to read the man pages for the utilities listed below to verify that they are capable of working with image files.

To make an image, one can use dd as follows:

Working with digital cameras

In order for some of the utilities listed in the next section to work with flash media, the device in question needs to be mounted as a block device (i.e., listed under /dev). Digital cameras operating in PTP (Picture Transfer Protocol) mode will not work in this regard. PTP cameras are transparently handled by libgphoto and/or libptp. In this case, «transparently» means that PTP devices do not get block devices. The alternative to PTP mode, USB Mass Storage (UMS) mode, is not supported by all cameras. Some cameras have a menu item that allows switching between the two modes; refer to your camera’s user manual. If your camera does not support UMS mode and therefore cannot be accessed as a block device, your only alternative is to use a flash media reader and physically remove the storage media from your camera.

List of utilities

  • dvdisaster — Additional error protection for CD/DVD media.

https://sourceforge.net/projects/dvdisaster/ || dvdisasterAUR

  • ext4magic — recover deleted or overwritten files on ext3 and ext4 filesystems.

https://sourceforge.net/projects/ext4magic/ || ext4magic

  • Foremost — Console program to recover files based on their headers, footers, and internal data structures. This process is commonly referred to as data carving. The headers and footers can be specified by a configuration file or command line switches can be used to specify built-in file types.
Читайте также:  Как почистить сопла принтера epson l3151

http://foremost.sourceforge.net/ || foremost

  • PhotoRec — File data recovery software designed to recover lost files including video, documents and archives from hard disks, CD-ROMs, and lost pictures (thus the Photo Recovery name) from digital camera memory.

https://www.cgsecurity.org/ || testdisk

  • Scalpel — File carving and indexing application originally based on Foremost, although significantly more efficient. It allows an examiner to specify a number of headers and footers to recover filetypes from a piece of media.

https://github.com/sleuthkit/scalpel || scalpel-gitAUR

  • TestDisk — Data recovery software primarily designed to help recover lost partitions and/or make non-booting disks bootable again when these symptoms are caused by faulty software: certain types of viruses or human error (such as accidentally deleting a Partition Table).

https://www.cgsecurity.org/ || testdisk

Ext4Magic

ext4magic is a recovery tool for the ext3 and ext4 file system.

The factual accuracy of this article or section is disputed.

If you erroneously deleted some files/folders, do not turn off your computer. For best results (actually, for decent results) you must save the ext4 journal somewhere.

Immediately open a terminal and dump a copy of the filesystem journal:

Depending on whether the deleted files are on your root partition, you’ll want to save the journal do different locations: for root partitions, mount an external drive and dump the journal there; for non-root partitions, any other partition will do. Avoid saving to /tmp , because your data may be cleaned up.

If the deleted files are on your root partition, you should turn off the computer after saving the journal. Do so by holding the power button until it turns off, because this prevents additional writes to the disk. Proceed with the process from the Arch bootable media. Otherwise, you may proceed with your booted system, after unmounting the affected partition ( sudo umount /dev/sdXY or sudo umount /home , for example).

To list the recoverable files:

  • -a applies a filter so that only files deleted after a certain Unix epoch are shown; in this example, it’s set at the last 2 hours. If you’re running from Arch bootable media, you may want to change the timezone ( export TZ=»Europe/Berlin» ) before using absolute times. If not specified, the default is the last 24h.
  • -f indicates that ext4magic should only list files in a certain subfolder. This path is relative to the partition root.
  • -j indicates that ext4magic should use specific backup of the journal; otherwise it uses the regular system journal, which doesn’t contain record of deletion if you’ve restarted your computer.
  • -l lists the deleted files

Files are listed with their recoverability percentage in the first column.

To actually recover all files with 100% recoverability, run this command:

  • -d indicates the target where the recovered files will be stored
  • -r indicates that only files with 100% recoverability should be recovered; -m will try to recover more files, but will take longer.

If you’re missing the journal backup you may still try to recover your files, but expect poor results.

To recover all files, deleted in the last 24 hours:

To recover a directory or file:

The small R flag -r will only recover complete files, that were not overwritten. To also recover broken files, that were partially overwritten, use the big R flag -R . This will also restore not-deleted files and empty directories.

The default destination is ./RECOVERDIR which can be changed by adding the option -d path/to/dest/dir .

If a file exists in the destination directory, the new file is renamed with a trailing hash sign # .

To recover files deleted after ‘five days ago’:

To use a file list:

The difference between the big L flag -L and the small L flag -l is the same as between the two R flags -R and -r (see above).

Use grep -a to preserve binary file names.

Using a file list allows to filter the files, for example by file extension:

. or to split the file list:

TestDisk and PhotoRec

TestDisk and Photorec are both open-source data recovery utilities licensed under the terms of the GNU Public License (GPL).

TestDisk is primarily designed to help recover lost partitions and/or make non-booting disks bootable again when these symptoms are caused by faulty software, certain types of viruses, or human error, such as the accidental deletion of partition tables. TestDisk detects numerous filesystem including NTFS, FAT12, FAT16, FAT32, exFAT, ext2, ext3, ext4, btrfs, BeFS, CramFS, HFS, JFS, Linux Raid, Linux Swap, LVM, LVM2, NSS, ReiserFS, UFS, XFS. It can also undelete files from FAT, NTFS, exFAT and ext2 filesystem.

Читайте также:  Драйвер на принтер canon g3411 для виндовс 10

TestDisk allows to fix partition tables, recover deleted partitions, recover FAT32 boot sector from its backup, rebuild FAT12/FAT16/FAT32 boot sectors, fix FAT tables, rebuild NTFS boot sector and more.

PhotoRec is file recovery software designed to recover lost files including photographs (Hint: PhotographRecovery), videos, documents, archives from hard disks and CD-ROMs. PhotoRec ignores the filesystem and goes after the underlying data, so it will still work even with a re-formatted or severely damaged filesystems and/or partition tables.

Installation

Install the testdisk package, which provides both TestDisk and PhotoRec.

Usage

After running e.g. ddrescue to create image.img, photorec image.img will open a terminal UI where you can select what file types to search for and where to put the recovered files. There is very good documentation on their wiki.

Files recovered by photorec

The photorec utility stores recovered files with a random names(for most of the files) under a numbered directories, e.g. ./recup_dir.1/f872690288.jpg , ./recup_dir.1/f864563104_wmclockmon-0.1.0.tar.gz .

See also

  • How to get the original filenames: PhotoRec FAQ
  • How to add your own custom file signature: CGSecurity Wiki
  • Wiki (TestDisk): https://www.cgsecurity.org/wiki/TestDisk
  • Wiki (Photorec): https://www.cgsecurity.org/wiki/PhotoRec
  • Homepage: https://www.cgsecurity.org/

e2fsck

e2fsck is the ext2/ext3 filesystem checker included in the base install of Arch. e2fsck relies on a valid superblock. A superblock is a description of the entire filesystem’s parameters. Because this data is so important, several copies of the superblock are distributed throughout the partition. With the -b option, e2fsck can take an alternate superblock argument; this is useful if the main, first superblock is damaged.

To determine where the superblocks are, run dumpe2fs -h on the target, unmounted partition. Superblocks are spaced differently depending on the filesystem’s blocksize, which is set when the filesystem is created.

An alternate method to determine the locations of superblocks is to use the -n option with mke2fs. Be sure to use the -n flag, which, according to the mke2fs manpage, «Causes mke2fs to not actually create a filesystem, but display what it would do if it were to create a filesystem. This can be used to determine the location of the backup superblocks for a particular filesystem, so long as the mke2fs parameters that were passed when the filesystem was originally created are used again. (With the -n option added, of course!)«.

Installation

Both e2fsck and dumpe2fs are included in the base Arch install as part of e2fsprogs .

Working with raw disk images

This article or section is a candidate for merging with QEMU.

If you have backed up a drive using ddrescue or dd and you need to mount this image as a physical drive, see this section.

Mount the entire disk

To mount a complete disk image to the next free loop device, use the losetup command:

Mounting partitions

In order to be able to mount a partiton of a whole disk image, follow the steps above.

Once the whole disk image is mounted, a normal mount command can be used on the loop device:

This command mounts the first partition of the image in loop0 to the folder to the mountpoint /mnt/example . Remember that the mountpoint directory must exist!

Getting disk geometry

Once the entire disk image has been mounted as a loopback device, its drive layout can be inspected.

Using QEMU to repair NTFS

With a disk image that contains one or more NTFS partitions that need to be chkdsk ed by Windows since no good NTFS filesystem checker for Linux exists, QEMU can use a raw disk image as a real hard disk inside a virtual machine:

Then, assuming Windows is installed on primary.img , it can be used to check partitions on /path/to/DamagedDisk.img .

Text file recovery

It is possible to find deleted plain text files on a hard drive by directly searching on the block device. A preferably unique string from the file you are trying to recover is needed.

Use grep to search for fixed strings ( -F ) directly on the partition:

Hopefully, the content of the deleted file is now in OutputFile, which can be extracted from the surrounding context manually.

Источник

Поделиться с друзьями
КомпСовет
Adblock
detector