- Бэкап Linux и восстановление его на другом железе
- 1. Создание бэкапа
- Восстановление бэкапа на другом железе
- Какие папки включить в резервную копию?
- 8 ответов
- crontabs
- NFS разделяет
- sudoers
- apache config
- autofs [ 1114]
- fstab
- хосты
- самба
- systemd
- mlocate
- home dir можно сохранить, если переустановить Ubuntu
- Full and Incremental Backups Using Tar Linux Command
- Requirements:
- Part 1: Performing a Full and Incremental Backups Using Tar Linux Command.
- Here’s the backup scenario I’m using in my work:
- Taking a Full and Incremental Backup Using Tar command.
- What action the above tar command exactly do?
- Why the above tar command do that action / behavior?
- Examples of Naming the full and incremental backups naming and the snapshot files.
- Part 2: Writing The Shell Backup Script And Add It To Cron Job To Automate the Backup Process.
- Part 3: Removing Old / Expired Backups.
- What is the ideas behind the retention script we created?
- Part 4: Merging The Backup Script And the Retention Period Script Into One.
- Summary
Бэкап Linux и восстановление его на другом железе
Я работаю в организации с маленьким штатом, деятельность тесно связана с IT и у нас возникают задачи по системному администрированию. Мне это интересно и частенько я беру на себя решение некоторых.
На прошлой неделе мы настраивали FreePBX под debian 7.8, нанимали фрилансера. В процессе настройки оказалось, что сервер (да, я так называю обычный PC) не хочет грузится с HDD при подключенных USB 3G модемах, которые мы используем для звонков на мобильные, колупание BIOSа не помогло. Непорядок. Решил, что нужно перенести его на другую железяку. Так появилось сразу две связанные задачи:
- сделать бэкап сервера;
- восстановить бэкап на другом железе.
Гугление не дало внятных ответов, как это сделать, пришлось собирать информацию кусками и пробовать. Всякие acronis’ы отбросил сразу, ибо не интересно.
Опыт общения с linux-системами у меня небольшой: настройка VPN сервера на open-vpn, ftp-сервера и еще пара мелочей. Сам себя я характеризую как человека умеющего читать маны и править конфиги 🙂
Ниже я описываю свой частный случай и почему я поступил именно так. Надеюсь, новичкам будет полезно, а бородатые админы улыбнутся вспомнив молодость.
Начинаем копать теорию:
Второй способ требует наличия внешнего жесткого диска объемом не меньше раздела, который архивируем. Да и что с ним потом делать, непонятно, хранить на полочке? Остановился на tar, чуть сложнее в реализации, нужно будет создать MBR, но время создания/восстановления архива существенно меньше, хранить бэкап проще, полтора гига можно закинуть в облако и скачать, когда будет нужно. Записывать его можно на ту же live-флэшку, с которой буду грузиться.
Итак, план действия:
1. Создание бэкапа
Грузимся с live-флэшки, у меня это debian-live-7.8.0-amd64-standard.
Переключаемся на root:
Монтируем раздел, который будем архивировать, у меня это sda1, чтобы случайно не наломать дров, монтируем только для чтения. Посмотреть все свои разделы можно при помощи команд ls /dev | grep sd или df -l
Наша флэшка уже примонтирована, но в режиме только чтения, нужно перемонтировать для чтения-записи, чтобы писать туда бэкап.
Все готово для создания архива
Здесь у нас параметры: c — создать архив, v — выводить информацию о процессе, z — использовать сжатие gzip, p — сохраняем данные о владельцах и правах доступа, f — пишем архив в файл, путь к файлу, —exclude — исключаем из архива каталог (я исключил каталоги с записями разговоров и каталог с бэкапами FreePBX), /mnt/ — каталог, который архивируем.
Ждем… у меня вся подготовка и создание архива заняли 10 минут. Будь флэшка быстрее, уложился бы в 7-8 минут.
Складываем архив в надежное место за пределами офиса.
Восстановление бэкапа на другом железе
2. Размечаем диск, создаем файловую систему
Грузимся с live-флэшки, у меня все та же debian-live-7.8.0.
Переключаемся на root:
Размечаем диск. Мне понравилась утилита с псевдографическим интерфейсом cfdisk. Там все просто и понятно.
Удаляем все имеющиеся разделы. Я создал два новых раздела, один на 490 Gb под / (sda1) и 10 Gb под swap (sda2) в конце диска, т.к. он практически не будет задействован. Проверим типы разделов. Который под систему должен иметь тип 83 Linux, второй — 82 Linux swap / Solaris. Помечаем системный раздел загрузочным (bootable), сохраняем изменения и выходим.
Cоздаем файловую систему на первом разделе.
3. Распаковываем архив.
Монтируем отформатированный раздел
Распаковываем архив прямо с флэшки
Параметр —same-owner — сохраняет владельцев у распаковываемых файлов, x — извлекаем из архива, v — выводить информацию о процессе, p — сохраняем права доступа, f — указываем файл, который распаковываем, C — распаковываем в категорию.
4. Создаем MBR на новом диске.
Чтобы корректно создать загрузочную запись, монтируем рабочие каталоги к нашему будущему root-каталогу, у меня это /mnt. Каталоги /dev и /proc сейчас используются live-системой, используем параметр bind, чтобы они были доступны сразу в двух местах:
Переключаемся на новую систему используя chroot:
Делаем swap-раздел для новой системы:
Подключаем его же:
Чтобы grub работал, нужно указать ему правильные UUID разделов в fstab, сейчас там прописаны разделы предыдущей системы:
Открываем второй терминал (Alt+F2) под root:
И видим текущие UUID разделов.
Вручную переписываем их в fstab переключаясь между Alt+F1 и Alt+F2. Да, муторно, но попытки копировать занимали у меня больше времени, чем переписывание. Сохраняем fstab.
Устанавливаем grub2. У меня один физический диск, поэтому ставим его на sda:
На чистый диск должно встать без ошибок. Обновляем информацию из fstab:
Возвращаемся в Live-систему:
Размонтируем все каталоги:
Если вылазят процессы, которые используют эти каталоги, убиваем их используя fuser.
Все, поехали. Грузимся с жесткого диска:
Здесь статья должна была закончиться, но у меня возникли проблемы с подключением к интернету. Сервер видит сеть, видит компьютеры в ней, но в интернет не ходит… а это как бы важно для телефонии.
5. Тестирование и устранение неполадок.
Показывет интерфейсы eth1 и lo, гугление сказало, что gateway можно прописать только подключению eth0, остальные рассчитаны только на работу внутри сети.
Похоже, отсутствие eth0 вызвано способом переноса системы. Находим файл, который отвечает за нумерацию интерфейсов, смотрим туда:
Действительно, там два активных интерфейса, определенных MAC’ами. Комментируем первый, второму прописываем eth0.
Перезапуск /etс/init.d/networking не помог, поэтому перезагружаемся:
Подключаем донглы, проверяем, все работает.
Спасибо за внимание.
Источник
Какие папки включить в резервную копию?
Это сработало для меня:
Откройте редактор конфигурации и настройте
/apps/nautilus/preferences/ media_automount = true media_automount_open = true
Затем установите usbmount:
sudo apt-get install usbmount
8 ответов
Мои резервные наборы в настоящее время содержат
Обратите внимание, что это для сервера, поэтому резервное копирование таких вещей, как / etc, сохраняет всю мою конфигурацию для моих служб, у меня есть веб-серверы в / srv (хотя, если вы они должны быть в / var / www, они все еще будут в этом наборе резервных копий), у меня есть различные сценарии и вещи, настроенные в / usr / local, и т. д. Резервное копирование / home вместо / home / myusername предназначено для сохранения все пользователи. Если все, что вы хотите сохранить, это ваши пользовательские данные, вам нужен только ваш домашний каталог.
Большинство людей просто делают резервную копию своего домашнего каталога: /home/$USER/ . Если вы хотите сделать резервную копию файлов конфигурации и настроек, они хранятся в папках и файлах в вашем домашнем каталоге, которые начинаются с. (Точка). Составьте список пакетов, которые вы используете (и PPA), и вам будет легко переустановить все ваши пакеты, если вам нужно. Или используйте команду, описанную в в этом комментарии .
Deja Dup Backup — отличный инструмент, который по умолчанию используется в Ubuntu. Другие параметры включают в себя командную строку (rsync, rsnapshot, rdiff-backup и т. Д.).
Наконец, чтобы сделать резервную копию всего диска в виде образа, посмотрите clonezilla .
Если я переустанавливаю свою настольную систему, я копирую
- /etc
- /var , Я слишком ленив для исключения некоторых подпапок
- /opt
/home находится на отдельном разделе и делали резервное копирование каждый день.
После переустанавливания я восстанавливаю части от своего резервного копирования, в котором я действительно нуждаюсь.
С этой стратегией все мои конфигурации, местные почты и crontab конфигурации безопасны, и я должен переустановить свои необходимые приложения только.
Мои персональные сценарии сохраняются в моей домашней папке (ежедневное резервное копирование, помните?), поэтому я не использую /usr/local .
Просто напоминание, если вы используете DejaDup (или что-то еще на самом деле), также исключите любые папки облачного хранилища (вероятно, у вас дома), такие как Dropbox. Если вы платите за хранилище s3, это может быть плохой ошибкой.
Давайте соберем список файлов здесь. Я сделал этот пост «сообщество вики».
Конечно, это зависит от человека к человеку. Мой используется в основном как веб-сервер и NFS-сервер.
crontabs
NFS разделяет
sudoers
apache config
autofs [ 1114]
fstab
хосты
самба
systemd
mlocate
home dir можно сохранить, если переустановить Ubuntu
Необходимое резервное копирование зависит от конкретной системы *.
Так что это займет немного работы с вашей стороны, чтобы разобраться. Начните с выяснения того, что не нужно , необходимо создать резервную копию. Сначала посмотрите на ваш корневой каталог, а затем работайте в обратном направлении.
Например, cd /; ls -F дает мне:
/cdrom , /media и /mnt являются точками монтирования, поэтому не нуждаются в резервном копировании.
/dev , /lost+found , /proc , /run , /sys и /tmp автоматически воссоздаются при перезагрузке. [Я предполагаю, что ссылки: /initrd.img@ , /initrd.img.old@ , /vmlinuz@ , /vmlinuz.old@ восстанавливаются при переустановке загрузочной Ubuntu (я не уверен, какой).]
Вкл. моя система /root пуста (используйте sudo -s , чтобы открыть оболочку от имени пользователя root, чтобы просмотреть ее . будьте осторожны с exit сразу после проверки /root .)
/snap тоже пусто. Возможно, это точка монтирования.
/var содержит переменные данные, такие как системные журналы, почтовые каталоги и каталоги каталогов принтера, а также временные и временные файлы. «Теперь я сохраню их, за исключением / var / log. Ref: http: // www .tldp.org / LDP / Linux-Filesystem-Hierarchy / html / var.html )
/bin , /boot , /lib , /lib64 и /sbin предположительно будут получить перезагрузку через переустановку Ubuntu, если вы не занимаетесь разработкой системы или чем-то в этом роде. Вы можете создать их резервную копию или использовать новую установку для их восстановления.
/home должны быть в его собственной резервной копии . Будут времена, когда вам захочется восстановить только /home .
Это оставляет другие изменения, которые вы внесли в вашу систему в /etc , /opt , /srv и /usr . который вы также хотите сделать резервную копию, вместе или по отдельности.
Вот несколько страниц, которые могут помочь понять эти каталоги:
Связанное с этим мышление: Скажем, вы только что установили свежую Ubuntu. Что бы вы хотели сделать резервную копию? Ответ: ничего. Вы еще ничего не изменили, поэтому вы можете просто переустановить Ubuntu. Восстанавливает / bin, / etc, / root, / usr и т. Д.
Так что единственная причина, по которой вы можете сделать резервную копию / bin, это то, что вы изменили ее или добавили в нее. Таким образом, часть резервного копирования заключается в понимании того, где и когда оно создано и изменено. Просто знайте, что остальные из нас тоже борются с этим.
***** И, хотя вы не спрашивали, можно создать полные образы дисков или разделов. Это занимает много времени для резервного копирования и восстановления и может привести к остановке системы во время этой работы. И именно так я делал резервные копии своих систем Windows с помощью Acronis. Единственное, что они вам предоставляют, — это карта разделов и изображения с разделов, отличных от Linux. Теперь я делаю это до того, как реорганизовать разделы и до того, как протестирую свои функции восстановления из резервной копии.
(я очень открыт для предложений относительно того, как я мог бы сделать это лучше.)
Источник
Full and Incremental Backups Using Tar Linux Command
Posted by: Mohammed Semari | Published: August 6, 2016| Updated: August 6, 2016
In this article we will discuss the using of tar command to perform a full and incremental backups for files and directories in Linux systems. Tar is very useful tool in backing up files, directories, and even full systems “full OSes”, here will use it only to backing up data “file and directories” in the following scenario; will use it to perform a full backup every month “day one of every month” and perform a daily backup to the end of the month. We will use cron jobs to schedule “automate” the backup process and will use cron jobs to auto-remove the expired backups “backups which exceeded the retention period”.
This article will include a shell script that performs backups in both types and a shell script that performs tracking and removing expired backups. I’ll explain the idea of each script, and step by step to automate the whole process.
Requirements:
- In general you must have a root privilege to backup most of systems you will work with.
- You must have enough storage space to save your full and incremental backups.
- You should have some experience in using tar command simply by reading our Sysadmins Most Used Tar Command Examples in Linux article.
- Better to have a little experience in writing shell scripts, if No, never mind you can go and use my scripts with little modifications.
- Better to have a little experience in schedule tasks using cron jobs, if No, never mind I’ll show you how to schedule a cron jobs task.
After reading this three parts article, you will gain all the experience to protect your data “the first task sysadmins must master”.
So, let’s start.
Part 1: Performing a Full and Incremental Backups Using Tar Linux Command.
There are three kinds of backups. The simplest type is a ‘full’ or level 0 backup then come the differential backup and finally incremental backup. In this article I’ll only perform full backup and incremental backup to my data.
Full backup means taking a backup of all files and directories, in general, it takes longer time to finish than incremental backup and also needs a huge storage for saving it.
On the other hand, the incremental backup only takes the modified/changed/added files and directories and mark the deleted files and directories, since last taken backup “either full or incremental”, it takes less time and needs less space for saving it.
Here’s the backup scenario I’m using in my work:
- Taking a monthly full backup at day one of each month.
- Taking incremental backup daily from day 2 of each month to the last day of the month.
- After a certain period, I remove the old full and increment backups to save my storage space, this period is known as a retention period.
Taking a Full and Incremental Backup Using Tar command.
Here’s the tar command I use to take a full and incremental backup of my data, I’ll backup a daily modified image directory called uploads which has this full path “/var/discourse/shared/standalone/uploads/“, which daily updated with users photos. I’ll need two directories to save my backup files and my snapshot file, I’ll save my backups files in “/Backups/uploads/“, and save my snapshot file in “/Backups/snap_files/“. We are including a time-stamp in naming the compressed backup file “images_uploads-`date +%Y-%m-%d`.tar.gz“, and in naming the snapshot file “images_uploads-`date +%Y-%m`.snap“, you can see the difference between the two time-stamps. To perform a full and daily incremental backup for the uploads directory, I run the following command:
Let’s discuss the each option we have used in the above command for creating a full backup.
c –> Creates a new .tar archive file.
v –> Verbosely show the .tar file progress.
f –> File name type of the archive file.
z –> Compress the archive file with gzip
p or –preserve-permissions, –same-permissions –> Extract information about file permissions (default for superuser), no need to explicit add this option if you are the root user.
g or –listed-incremental=FILE –> Handle incremental backups with snapshot data in FILE
What action the above tar command exactly do?
The above command will perform a full backup at first time it run, then it will perform incremental backups every time it run after it’s first run till the last day of the current month. Then at the first day of the next month it’ll perform a full backup and will perform incremental backups till the end of the month, and so on. Sure you need to schedule this task to run daily using cron jobs, later in this article I’ll explain the cron job we use.
Why the above tar command do that action / behavior?
The above action / behavior because of the existence of “-g” option. the default behavior of tar archive is to perform a full backup every time it runs, but because we added “-g” option, it will perform a full backup at it’s first run and create a binary snapshot file “images_uploads-`date +%Y-%m`.snap” which specified by “-g” option and will write all the files it archived into this file. In the second time it runs, it’ll detect the existence of the snapshot file, so it’ll not create any new snapshot file and will use this file. By help of the existing snapshot file, it will only backup the modified/changed/added files, and will mark the deleted files in this incremental archive and will do this task every time it run.
At the first day of the next month, the tar command will not find the snapshot file of the current month because of the time-stamp in the snapshot file naming changed to be the current month, so the tar command will perform a full backup and create the new snapshot file for this month, and so on…
Examples of Naming the full and incremental backups naming and the snapshot files.
Let’s say we are in August and will run the above command today “which was at time of writing this post August 4, 2016”, the first backup will be full backup and will have this name “images_uploads-2016-08-04.tar.gz” and the tar will create a snapshot file with this name “images_uploads-2016-08.snap“. Next time the same tar command will run in this month “August”, it will find the snapshot file existing so it’ll perform an incremental backup with this name “images_uploads-2016-08-05.tar.gz“, and so on till the end of August.
Now, suppose we are at “September 01, 2016“, running the above tar will not find a snapshot with this name “images_uploads-2016-09.snap” so it’ll create it and do a full backup then every other day it’ll do incremental backup till the end of September, and will repeat this process forever “suppose the above tar command run daily in a cron job”.
Now you understand the idea of the backup scenario I perform, next part will discuss schedule / automate the above process.
Part 2: Writing The Shell Backup Script And Add It To Cron Job To Automate the Backup Process.
The above tar command must run daily to perform a full and incremental backups, but of course you will not run it manually, you need to schedule this task to run at a certain time every day using cron jobs.
Before we create the cron job, we will write the above command in a shell script and make it a general script. I’ll use variables to set the Backup files and the snapshot files backup location, and finally the directory you want to backup it.
Here’s our general tar backup shell script:
Now, save the above script with name “Server-Backup_V1.sh” in your administration scripts directory “if you have one”. As showed in comments in the above shell script, you only can change the values of four variables “Backup-Snapshot_file_name, Backups_Destination, Snapshots_Destination, and Data_to_be_Backed_up“. Set the values for those variables with the values in your backup system infrastructure. Values naming must be have a absolute path.
Now, it’s time to use the cron jobs, we will create a cron job that runs daily at 12 AM to execute the Server-Backup_V1.sh backup script.
In your terminal, run the following command:
And append the following cron job to the end of the existing jobs as follow:
Save then exit. Now your cron job will run daily at 12 AM to run your backup script located in “/home/mohammed.semari/Semari-Scripts/Server-Backup_V1.sh”
Part 3: Removing Old / Expired Backups.
Removing the old / expired backups is also known as “the backup retention period“, which is how long do you keep old backups files in your storage. It’s important to set the retention period carefully, the perfect case is to set it as long as you can, but this will need a large disk space. Feel free to set this value as you wish in your systems.
I’ll write a shell script to remove the backups files and snapshot files that older than one month. I’ll use the same variables naming used in the backup script, because at the end of this article, I’ll merge the two scripts into one, but now need to show you the ideas behind this retention script.
Here’s our backup retention shell script:
Now, save the above script with name “AutoRetention_V1.sh” in your administration scripts directory “if you have one”, and if you will use it alone, you need to run this script monthly using cron jobs just as what we did with the backup script. For me I’ll merge both scripts into one and run the new script daily at 12 AM.
Here’s the cron job in this case:
What is the ideas behind the retention script we created?
A good question, here’s the idea; simply we need to remove the old backups that created older than a specific period “in our case one month”. Because we only take a full backup once at the start of each month and incremental backup to the end of the month, we can not remove old backups file by file “If we removed only the full backup which taken at day one of the month, other incremental backups will worth nothing if the files we want to restore wasn’t changed since the full backup” So, we have to remove old backups month by month.
In the above script, I set the value of “Retention_period” to 3, this will do the following:
At the start of each month “day one” the “AutoRetention_V1.sh” script will remove the existing backups of the month before before the current month i.e suppose we are At August 01, and the script runs daily at 12 AM, the script will remove the backups file of June, and the snapshot file of June. At this case we have the backups and snapshot of July in our storage. The backup script will take it’s backups daily to the end of August, at September the “AutoRetention_V1.sh” script will remove the backups file of July, and now we have the backups and snapshots of August in our storage, and so on.
Part 4: Merging The Backup Script And the Retention Period Script Into One.
As the above two scripts use the same variable, it’s better for us to merge them into one script. We will name the new script “Full_Backup_Systems_V1.sh” and will run it daily at 12 AM. I’ll remove the comments from it as it exists in the above two scripts.
Here’s our final backup and retention period script:
Now, save the above script with name “Full_Backup_Systems_V1.sh” in your administration scripts directory, and use cron jobs to run it daily at 12 AM.
Summary
In this article, we discussed different ideas for backing up your system. We used tar Linux command to perform a full and incremental backups. In this article we created a full backup at first day in every month and incremental backups in other days till the end of the month. We used cron jobs to schedule the backup process. You have two options for using our two scripts “the backup script and the retention script” either use each of them separately or use the full backup script created by merging the two scripts. All needed from you is to change some values of variables in our scripts.
I hope this article is good enough for you.
See you in other articles
Источник