Создать бэкап системы linux

Introduction

Backup and recovery is essential. Failure to have verified backup and recovery procedures puts your data at risk of loss. Users often only learn this lesson after critical information they require is permanently lost. Attempting to recover from data loss can be both time consuming and extremely difficult. So learn from others mistakes, and ensure beforehand that you have a system in place that protects your data and suits your needs.

  • Why? — Why are you protecting yourself against disaster? Does it matter if you lose data? What losses will you suffer ($$$)?
  • What? — What are you going to backup? Your entire hard drive or just some of the data?
  • When? — When is the best time to backup your system? How often will you perform a backup? When will you use full backups and incremental backups.
  • Where? — Where will the backups be stored? On-site? Off-Site? Cloud?
  • Medium? — Attached storage (usb stick, usb hard drive, tape drive), backup server?

Backup

Types of Backup

  • Recovery time objective (RTO): How fast should data be recovered? Can you continue to operate if data recovery is not recovered for a day, a week, etc?
  • Recovery point objective (RPO): How much data can be lost. Can you lose two hours, two days or two weeks of data?
example: if you can withstand losing one week of data then a weekly backup would be sufficient, but if you can only withstand losing one day then you would need to employ a nightly backup (or a variation)

This document will cover three basic types of backup; Full, Incremental, and Differential.

Full: A full backup backs up all the files in the back up target.

Incremental: An incremental backup backs up all the files that have changed since the last backup.

Differential: A differential backup backs up all the files that have changed since the last full backup.

Backup Methods

  • manual — Manual backup would be initiated on a schedule by the user and is the most common method for home users to backup their files. This method is also the least reliable.
  • local automated — Automated backups that target a hard drive or tape drive attached to the physical box being backed up fall into this category. Advanced home users and small businesses will often use this method.
  • remote automated — Automated backups that target a hard drive, tape drive or virtual tape library (VTL) over the network fall into this backup. This type of backup is often used by businesses that have money they can dedicate to the process of backup. As the organization becomes more mature they may even stage the backup on multiple mediums and increase the distance between backup and production systems.
Читайте также:  Linux посмотреть модель монитора

mtime, atime and ctime

    mtime — modification time; this value is changed when the contents of the file is changed.

note: file system backups change atime while raw device backups will not. If you are implementing incremental or differential backups this is important

Recovery

note: many people consider only the backup part of this process and do nothing to verify that the backup can be restored. It is very important to test that your backup process is working and that data can be recovered.
  • Restore many single files
  • Restore an older version of a file
  • Restore an entire folder
  • Restore an entire drive and compare the checksum

If you do not test you may find out that nothing was being backed up when you need to restore the files in reality.

Источник

System backup

A system backup is the process of backing up the operating system, files and system-specific useful/essential data. [It] primarily ensures that not only the user data in a system is saved, but also the system’s state or operational condition. This helps in restoring the system to the last-saved state along with all the selected backup data. [1]

Using Btrfs snapshots

Using LVM snapshots

Using rsync

Using tar

Using SquashFS

Bootable backup

Having a bootable backup can be useful in case the filesystem becomes corrupt or if an update breaks the system. The backup can also be used as a test bed for updates, with the testing repo enabled, etc. If you transferred the system to a different partition or drive and you want to boot it, the process is as simple as updating the backup’s /etc/fstab and your boot loader’s configuration file.

This section assumes that you backed up the system to another drive or partition, that your current boot loader is working fine, and that you want to boot from the backup as well.

Update the fstab

Without rebooting, edit the backup’s fstab by commenting out or removing any existing entries. Add one entry for the partition containing the backup like the example here:

/dev/sdaX / ext4 defaults 0 1

Remember to use the proper device name and filesystem type.

Update the boot loader’s configuration file

For Syslinux, all you need to do is duplicate the current entry, except pointing to a different drive or partition.

Tip: Instead of editing syslinux.cfg , you can also temporarily edit the menu during boot. When the menu shows up, press the Tab key and change the relevant entries. Partitions are counted from one, drives are counted from zero.

For GRUB, it is recommended that you automatically re-generate the main configuration file. If you want to freshly install all GRUB files to somewhere other than /boot , such as /mnt/newroot/boot , use the —boot-directory flag.

Also verify the new menu entry in /boot/grub/grub.cfg . Make sure the UUID is matching the new partition, otherwise it could still boot the old system. Find the UUID of a partition with lsblk:

$ lsblk -no NAME,UUID /dev/sdXY 

where /dev/sdXY is the desired partition (e.g. /dev/sdb3 ). To list the UUIDs of partitions GRUB thinks it can boot, use grep:

# grep UUID= /boot/grub/grub.cfg

First boot

Reboot the computer and select the right entry in the boot loader. This will load the system for the first time. All peripherals should be detected and the empty folders in / will be populated.

Читайте также:  Epson 1170 драйвер linux

Now you can re-edit /etc/fstab to add the previously removed partitions and mount points.

Snapshots and /boot partition

If your file system supports snapshots (e.g., LVM or Btrfs), these will most likely exclude the /boot partition or ESP.

You can copy the boot partition automatically on a kernel update to your root partition with a pacman hook (make sure the hook file is owned by root):

/etc/pacman.d/hooks/95-bootbackup.hook
[Trigger] Operation = Upgrade Operation = Install Operation = Remove Type = Path Target = usr/lib/modules/*/vmlinuz [Action] Depends = rsync Description = Backing up /boot. When = PostTransaction Exec = /usr/bin/rsync -a --delete /boot /.bootbackup

Источник

Бэкап 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.

Второй способ требует наличия внешнего жесткого диска объемом не меньше раздела, который архивируем. Да и что с ним потом делать, непонятно, хранить на полочке? Остановился на 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, сейчас там прописаны разделы предыдущей системы:

Открываем второй терминал (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 не помог, поэтому перезагружаемся:

Источник

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