Which files to backup linux

What directories do I need to back up?

What are the directories one should back up, in order to have a backup of all user-generated files? From a vanilla debian install, I can do enough apt to get the packages that I want. So if I don’t want to backup the entire system, where all in the filesystem do user-generated configuration and data files reside?

Missing in all of these answers is what happens after you back the files up. Do you just copy them back once the new install completes? What problems could arise when you do that?

I think I’m just identifying a flaw that even Linux has. Hopefully maybe it will affect future design of the OS.

+1 for not using «backup» as a verb. I get tired of seeing otherwise intelligent people use it that way.

7 Answers 7

As this question has many different answers, the following list should combine the suggestions into one comprehensive list:

Under most circumstances you want to backup these:

  • /home/ for user data and configuration.
  • /etc/ for system wide configuration files.
  • /var/ contains a mix of directories you usually want to backup and those you don’t want to backup. See below for a more detailed explanation.

Some more directories to consider are:

  • /usr/local/ hand-installed packages (i.e. not installed through apt) are installed here. If you have packages installed here, you may want to backup the whole directory, so you don’t have to reinstall them. If the packages themselves aren’t important to you, it should be enough to backup /usr/local/etc/ and /usr/local/src/ .
  • /opt/ if you didn’t store anything here, you don’t need to back it up. If you stored something here, you are in the best position to decide, if you want to back it up.
  • /srv/ much like /opt/ , but is by convention more likely to contain data you actually want to backup.
  • /root/ stores configuration for the root user. If that is important to you, you should back it up.

/var/

/var/ contains many files you want to backup under most circumstances, but also some you don’t want to backup.

You probably want to backup these:

  • /var/lib/ this directory contains variable state data for installed applications. Depending on the application you want to backup that state or you don’t. If you want to be on the safe side, you can just back up everything. Otherwise you can look at each sub-directory and decide for yourself if the data contained is important enough to you to back it up.
  • /var/mail/ you normally want to backup local mails.
  • /var/www/ if your web root is located here and this is the only place where your web content is stored, you want to back it up.
  • /var/games/ you may want to backup these, if system wide game data is important enough for you (not many games use this storage though).
  • /var/backups/ usually contains files that are automatically generated from other data that you usually want on a backup, but that would take an unnecessary amount of space in the backup or is otherwise cumbersome to backup. For example dpkg dumps a list of installed packages here, so you can later know which packages to install after restoring the backup. You probably want to backup this.
  • /var/spool/cron/crontabs/ might contain many commands or a complex schedule, even with dependencies on other systems, that has taken considerable effort to put together.
Читайте также:  Dos prompt on linux

You probably don’t want to backup these:

  • /var/cache/ contrary to the name, some contents of this directory are important, so check each subdirectory individually, as a rule of thumb, everything you put here yourself is important. You also might want to backup /var/cache/debconf/ .
  • /var/lock/ locks usually (always) don’t need to be backed up.
  • /var/run/ contains data that is only important for your running system, i.e. when you shutdown you system, it will not be needed any more.
  • /var/spool/ (other than /var/spool/cron/crontabs , see above) normally important data shouldn’t be stored here, but you might want to check.

You have to decide yourself on these:

  • /var/local/ you normally know if you stored something here and whether you want it on a backup or not.
  • /var/opt/ see /var/local/ or better check if something important is stored here.
  • /var/log/ depends on whether your logs are important to you and if you have enough space to store them (they might take a lot of backup space over time).

Источник

Бэкап 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-флэшку, с которой буду грузиться.

Читайте также:  Не хватает прав linux
Итак, план действия:
  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.

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

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

Читайте также:  Linux перенос содержимого папки
5. Тестирование и устранение неполадок.

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

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

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

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

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

Источник

Which files do I need to backup to keep my Linux user settings?

I need to accomplish a clean install after a bad graphics driver issue. Which are the files I must backup to keep all users settings in Linux? My distro is fuduntu.

Basically you need to backup your /home directory, but depending on your usage or installations it would help to backup /etc /usr and /var . But chances are that you copy a bad config file over to the fresh system. I’d recommend to fix the problem instead of doing a clean install.

I had tryed [code] yum history -undo [code] but it didn’t help me. Also boouting with different vga modes «vga=ask» is helpless. Just terminal is accesible. So i can rm or copy or made other files operations. It freeze in boot a graphical shell gnome.

1 Answer 1

The bare minimum would be to keep the user’s own files within /home . Also, in order to know which files to keep from /etc it is beneficial to use a system like etckeeper that can track history of changes to /etc and who made them. IE — were they distribution changes, or changes that you made?

For the back up itself, I always copy the following:

/usr/local /usr/share /home /var /etc /root 

There are ways to back these up using Rsync to a separate area, using hardlinks so that additional space is not used on subsequent backups.

You can then restore /home/* as is, but you will want to pick specific files/folders as needed from /var and /etc . You will know if you need something specific from /usr/local , because most likely you will have put it there purposely.

The contents of /var and /usr/share can be tricky. Apache, mediawiki, wordpress, and various other services store data in either. You should know if you have any data stored in these by the configuration you did when you set up these services. If you don’t run any ‘server’ or ‘web’ services, you may be safe not backing these up, but it’s always wiser to backup than to wish you had backed up.

Unless you have hand-edited things in /etc you probably are safe with a clean config. If you do have hand-made-changes in /etc , it is best to port them over by hand so you know exactly what you are introducing to the clean system.

/opt may also be a directory of concern. It is usually created when installing software distributed with it’s own installer from software outside of your distribution. Backing up this is an option, but you may want to re-install those packages — as they have configurations that require links back into /etc

Источник

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