Image backup linux system

How to make a disk image and restore from it later?

I’m a new Linux user. I’ve reinstalled my Wubi from scratch at least ten times the last few weeks because while getting the system up and running (drivers, resolution, etc.) I’ve broken something (X, grub, unknowns) and I can’t get it back to work. Especially for a newbie like me, it’s easier (and much faster) to just reinstall the whole shebang than try to troubleshoot several layers of failed «fixing» attempts. Coming from Windows, I expect that there is some «disk image» utility that I can run to make a snapshot of my Linux install (and of the boot partition!!) before I meddle with stuff. Then, after I’ve foobar’ed my machine, I would somehow restore my machine back to that working snapshot. What’s the Linux equivalent of Windows disk imagers like Acronis True Image or Norton Ghost? Note: I found a similar question: Easy backup/restore of installed system?

Torben, under the Wubi folder (usually C:\UBUNTU, but may be some other drive & folder), you’ll find not only the loopback disk images created for your Ubuntu install, but also some other important files (like the Wubi loader). Sorry if it’s a guess, but I think it’s an educated one. 😉 Maybe (’cause I really have never tried — sorry — but wouldn’t hurt if you try it — I would) if you backup that folder while the system is in a good state, you can take Wubi back by replacing the good state over the non-functional one.

Please post this as an answer, because it sounds like a good way, specifically for Wubi installations! After my last fubar I installed a «real» Ubuntu, not Wubi, so this little trick will go into my drawer for next time I find myself in that spot.

You can just copy the files and the master boot record (freesoftwaremagazine.com/articles/…) and you’ll be fine.

Acronis True Image can capture an accurate backup while the system is running. All of the answers below except the one that mentions Ghost for linux fail because they don’t actually replace the functionality of Acronis and Ghost. There is a common belief that backups can be made on the system on which they are running. Although this is true, the backups created stand the risk of not restoring properly due to files being changed in the file-system as the backup is being made, making the backup inconsistent with itself.

12 Answers 12

With dd

dd is the low level utility that you can use to accomplish this task. It’s essentially a low level byte-for-byte copy utility. If you want the «UNIX» way of accomplishing this, then read on.

All references to the file system and hard disks are located locally on the virtual /dev/ filesystem. There are a multitude of «nodes» in /dev/ that are interfaces to almost all the devices on your computer. For example, /dev/hda or /dev/sda would refer to the first hard drive in your system (hda vs sda depends on the hard drive), and /dev/hda1 would refer to the first partition on your hard drive.

Читайте также:  Linux desktop for gaming

The most straight forward way to make a raw image of your partitions is to use dd to dump the entire partition to a single file (remember the OS access the partitions /dev/sda1 through a file interface). Make sure you are on a larger partition or on a secondary drive and perform the following command:

dd if=/dev/hda1 of=./part1.image to backup (repeat for different partitions) dd if=./part1.image of=/dev/hda1 to restore. When you backup /dev/hda1 this partition should be unmounted (or mounted read-only) to avoid potencial corruption.

You can use the exact same command to back up the entire hard disk (replace hda1 with hda ). You can then use any compression program (gunzip, zip, bzip) to compress the file for storage. You can use this same technique to make rote copies of entire partitions to make clones of your computer.

There is one limitation though, when restoring the backup: The partition needs to be the same size (or bigger) as the partition you took the image from, so this limits your options in case of a restore. However, you can always expand the partition after you’ve restored the backup using gparted or parted . The picture gets even muddier when you are trying to restore entire disk copies. However, if you are restoring the backup to the same exact hard drive, you don’t need to worry about this at all.

However, if you want a «friendlier» utility à la Norton Ghost then this suggestion might not be for you.

Источник

Бэкап Linux и восстановление его на другом железе

Я работаю в организации с маленьким штатом, деятельность тесно связана с IT и у нас возникают задачи по системному администрированию. Мне это интересно и частенько я беру на себя решение некоторых.

На прошлой неделе мы настраивали FreePBX под debian 7.8, нанимали фрилансера. В процессе настройки оказалось, что сервер (да, я так называю обычный PC) не хочет грузится с HDD при подключенных USB 3G модемах, которые мы используем для звонков на мобильные, колупание BIOSа не помогло. Непорядок. Решил, что нужно перенести его на другую железяку. Так появилось сразу две связанные задачи:

Опыт общения с linux-системами у меня небольшой: настройка VPN сервера на open-vpn, ftp-сервера и еще пара мелочей. Сам себя я характеризую как человека умеющего читать маны и править конфиги 🙂

Ниже я описываю свой частный случай и почему я поступил именно так. Надеюсь, новичкам будет полезно, а бородатые админы улыбнутся вспомнив молодость.

Начинаем копать теорию:

По созданию бэкапов уйма статей, я для себя отметил два способа: tar — упаковывает и сжимает все файлы, при этом не сохраняется MBR, мой бэкап будет весить около 1.5 Gb; dd — делает полную копию раздела, включая MBR и всю область, где нет файлов, архив будет равен размеру раздела, в моем случае ~490 Gb.

Читайте также:  Установка linux on ios

Второй способ требует наличия внешнего жесткого диска объемом не меньше раздела, который архивируем. Да и что с ним потом делать, непонятно, хранить на полочке? Остановился на tar, чуть сложнее в реализации, нужно будет создать MBR, но время создания/восстановления архива существенно меньше, хранить бэкап проще, полтора гига можно закинуть в облако и скачать, когда будет нужно. Записывать его можно на ту же live-флэшку, с которой буду грузиться.

Итак, план действия:
  1. создание бэкапа;
  2. форматирование, разметка диска, создание файловой системы;
  3. восстановление бэкапа;
  4. создание MBR;
  5. тестирование и устранение неполадок.

1. Создание бэкапа

Грузимся с live-флэшки, у меня это debian-live-7.8.0-amd64-standard.

Монтируем раздел, который будем архивировать, у меня это sda1, чтобы случайно не наломать дров, монтируем только для чтения. Посмотреть все свои разделы можно при помощи команд ls /dev | grep sd или df -l

Наша флэшка уже примонтирована, но в режиме только чтения, нужно перемонтировать для чтения-записи, чтобы писать туда бэкап.

mount -o remount,rw /dev/sdb1 /lib/live/mount/medium 

Все готово для создания архива

tar -cvzpf /lib/live/mount/medium/backupYYYYMMDD.tgz --exclude=/mnt/var/spool/asterisk/monitor --exclude=/mnt/var/spool/asterisk/backup /mnt/ 

Здесь у нас параметры: c — создать архив, v — выводить информацию о процессе, z — использовать сжатие gzip, p — сохраняем данные о владельцах и правах доступа, f — пишем архив в файл, путь к файлу, —exclude — исключаем из архива каталог (я исключил каталоги с записями разговоров и каталог с бэкапами FreePBX), /mnt/ — каталог, который архивируем.

Ждем… у меня вся подготовка и создание архива заняли 10 минут. Будь флэшка быстрее, уложился бы в 7-8 минут.

Складываем архив в надежное место за пределами офиса.

Восстановление бэкапа на другом железе

2. Размечаем диск, создаем файловую систему

Грузимся с live-флэшки, у меня все та же debian-live-7.8.0.

Размечаем диск. Мне понравилась утилита с псевдографическим интерфейсом cfdisk. Там все просто и понятно.

Удаляем все имеющиеся разделы. Я создал два новых раздела, один на 490 Gb под / (sda1) и 10 Gb под swap (sda2) в конце диска, т.к. он практически не будет задействован. Проверим типы разделов. Который под систему должен иметь тип 83 Linux, второй — 82 Linux swap / Solaris. Помечаем системный раздел загрузочным (bootable), сохраняем изменения и выходим.

Cоздаем файловую систему на первом разделе.

3. Распаковываем архив.

Монтируем отформатированный раздел

Распаковываем архив прямо с флэшки

tar --same-owner -xvpf /lib/live/mount/medium/backupYYYYMMDD.tgz -C /mnt/ 

Параметр —same-owner — сохраняет владельцев у распаковываемых файлов, x — извлекаем из архива, v — выводить информацию о процессе, p — сохраняем права доступа, f — указываем файл, который распаковываем, C — распаковываем в категорию.

4. Создаем MBR на новом диске.

Чтобы корректно создать загрузочную запись, монтируем рабочие каталоги к нашему будущему root-каталогу, у меня это /mnt. Каталоги /dev и /proc сейчас используются live-системой, используем параметр bind, чтобы они были доступны сразу в двух местах:

mount --bind /dev /mnt/dev mount --bind /proc /mnt/proc 

Переключаемся на новую систему используя chroot:

Делаем swap-раздел для новой системы:

Чтобы grub работал, нужно указать ему правильные UUID разделов в fstab, сейчас там прописаны разделы предыдущей системы:

Читайте также:  Pantum m6500w linux driver

Открываем второй терминал (Alt+F2) под root:

И видим текущие UUID разделов.

Вручную переписываем их в fstab переключаясь между Alt+F1 и Alt+F2. Да, муторно, но попытки копировать занимали у меня больше времени, чем переписывание. Сохраняем fstab.

Устанавливаем grub2. У меня один физический диск, поэтому ставим его на sda:

На чистый диск должно встать без ошибок. Обновляем информацию из fstab:

Возвращаемся в Live-систему:

Размонтируем все каталоги:

umount /mnt/dev umount /mnt/proc umount /mnt 

Если вылазят процессы, которые используют эти каталоги, убиваем их используя fuser.

Все, поехали. Грузимся с жесткого диска:

Здесь статья должна была закончиться, но у меня возникли проблемы с подключением к интернету. Сервер видит сеть, видит компьютеры в ней, но в интернет не ходит… а это как бы важно для телефонии.

5. Тестирование и устранение неполадок.

Показывет интерфейсы eth1 и lo, гугление сказало, что gateway можно прописать только подключению eth0, остальные рассчитаны только на работу внутри сети.

Похоже, отсутствие eth0 вызвано способом переноса системы. Находим файл, который отвечает за нумерацию интерфейсов, смотрим туда:

nano /etc/udev/rules.d/70-persistent-net.rules 

Действительно, там два активных интерфейса, определенных MAC’ами. Комментируем первый, второму прописываем eth0.

Перезапуск /etс/init.d/networking не помог, поэтому перезагружаемся:

Источник

Linux Image Backup: Two Powerful Approaches to Disk Imaging

Linux image backup is a must-do for the ones who want to feel safe about their data, while using the open-source software. Handy Backup has already proved itself a fine Linux backup utility and currently does provide two ways for the reserving full image copies under Linux.

Linux Image Backup under Wine

The first approach is to run Handy Backup under Wine and enjoy its versatile functionality. The program does the job quite fine, though it might be not the most high-speed operating one. We can recommend this solution for those who hadn&#8217t a chance to use our product as a Linux image backup utility before.

The native Linux version is under development. Just wait a little and you get a monster, cross-platform backup & restore utility, capable of every reserving data task, you can think of!

Linux Disaster Recovery the Simple Way

Another solution we can recommend as a disk imaging software is Handy Backup Disaster Recovery. Comparing to the above Linux backup software, this one is much simpler. The product is intended for system recovery from its full system image. Linux image backup itself is not among the default Handy Backup Disaster Recovery features, but it becomes available after the license purchasing.

Say, you&#8217ve experienced a really bad hard drive crash, but have its&#8217 full backup stored at the external hard drive. In this case, for Linux disaster recovery you just need to create a recovery USB. It should contain the Knoppix distributive and some other stuff to make the recovery process easier (everything is available here, at the Handy Backup website). Then you connect the recovery USB to the computer and follow simple steps to quickly restore your Hard Drive.

Источник

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