Резервная копия линукс tar

Простые инкрементальные бэкапы в Linux с помощью TAR и GPG

Обожаю UNIX-way, тут бэкапы можно делать значительно более гибкими.

Для бэкапа home директории я использую обычный tar с инкрементацией и шифрую его своим gpg ключом.

Для других файлов, например, для бэкапов моих видео, которые я записываю для ютуба я использую rsync. RSYNC более рационально использовать, когда не критична синхронизация большого количества файлов

#!/bin/bash NOW=$(date +%Y%m%d%H%M) MNOW=$(date +%Y%m) BACKUP_HOME="/tmp/home/" EMAIL="devpew" ARCHIVES_DIR="/tmp/backup/" DOW=`date +%a` # Day of the week e.g. Mon DOM=`date +%d` # Date of the Month e.g. 27 DM=`date +%d%b` # Date and Month e.g. 27Sep if [[ ! -d $$ ]] then mkdir $$ else echo &>/dev/null fi tar --exclude-from=/home/dm/mybin/.backup.excludes -v -z --create --file $$/$.tar.gz --listed-incremental=$$/$.snar $BACKUP_HOME &> $$/$.log if [ $(ls -d $$/*.tar.gz 2> /dev/null | wc -l) != "0" ] then gpg -r $EMAIL --encrypt-files $$/*.tar.gz \ && rm -rf $$/*.tar.gz fi scp $$/$.tar.gz.gpg $$/$.snar dm@192.168.0.152:/home/dm/backup/$

Если нужен более гибкий инкремент второго уровня, например, по неделям, то можно использовать такие условия

DOW=`date +%a` # Day of the week e.g. Mon DOM=`date +%d` # Date of the Month e.g. 27 DM=`date +%d%b` # Date and Month e.g. 27Sep if [ $DOM = "01" ]; then echo 'this is monthly backup' fi if [ $DOW = "Sun" ]; then echo 'this is weekly backup' else echo 'this is daily backup' fi 

How it works

Теперь, коротко о том, что делает этот скрипт

Скрипт перейдет в указанную директорию для бекапов и создаст в ней директорию с именем года и месяца в формате “202205” если сейчас май 2022 года.

Далее все бэкапы за май будут находиться в этой папке.

Далее если в папке нет файла с инкрементом (например, мы впервые запустили скрипт или начался новый месяц) то у нас создастся полный бекап всей системы.

В дальнейшем при запуске этого скрипта будут создаваться инкременты от текущего полного бекапа

Кроме того появится файл с логом

После того как у нас сделался бекап, он у нас зашифруется нашим GPG ключом а файл TAR удалится.

После этого мы скопируем наш бэкап к нам на сервер

Exclude

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

➜ mybin cat /home/dm/mybin/.backup.excludes /tmp/home/Nextcloud /tmp/home/.cache /tmp/home/youtube-videos

Кроме того, ничего не будет работать, если вы поставите слэш в конце.

Читайте также:  Stop module loading linux

Например строка /tmp/home/Nextcloud будет работать, а вот строка /tmp/home/Nextcloud/ работать уже не будет. Так что будьте аккуратны

Если нужно распаковать

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

Расшифровать можно командой

gpg --output 202205122134.tar.gz --decrypt 202205122134.tar.gz.gpg

После этого, начнем распаковывать tar начиная с самого первого. Для начала распаковываем архив от первого числа.

tar --extract --verbose --listed-incremental=/dev/null --file=202205010101.tar.gz

И после этого распаковываем остальные инкременты, если нужно восстановить состояние системы, например, на 11 число, то нужно последовательно распаковать tar-архивы со 2 по 11 в ту же папку

Если это кажется слишком долгим процессом и вы часто восстанавливаете данные, то можно добавить инкремент второго уровня, например, недельный.

Или если вручную для вас это кажется слишком длительным процессом, можете накидать небольшой скрипт для распаковки. В простейшем случае так:

tar --extract --incremental --file file0.tar tar --extract --incremental --file file1.tar tar --extract --incremental --file file2.tar
for i in *.tbz2; do tar -xjGf "$i"; done;

Если нужно извлечь только конкретные каталоги из архива:

tar -xjGf levelX.tar --wildcards 'example/foo*' 'example/bar*'

Autorun

Если бы в убунте или дебиане, то вам нужно запускать этот скрпит через крон. В арче нет крона и автозапуск делается иначе. В этом примере будем запускать наш скрипт каждый день в 03:30

sudo nvim /usr/lib/systemd/system/backup.service
[Unit] Description=backup [Service] Type=simple ExecStart=/home/dm/mybin/backup
sudo nvim /usr/lib/systemd/system/backup.timer
[Unit] Description=my backup [Timer] OnCalendar=*-*-* 03:30:00 [Install] WantedBy=multi-user.target

После этого можем запустить наш сервис

sudo systemctl start backup.timer sudo systemctl enable backup.timer

После этого проверим добавился ли он командой

sudo systemctl list-timers --all
sudo systemctl status backup.timer

Remove old backups

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

Источник

Full system backup with tar

Reason: Uses a half-baked script instead of explaining basic options and referring to the manual, duplication with articles such as Help:Reading, numerous Help:Style issues (Discuss in Talk:Full system backup with tar)

This article will show you how to do a full system backup with tar.

Backing up with tar has the advantages of using compression that can help save disk space, and simplicity. The process only requires several steps, they are:

  1. Boot from a LiveCD
  2. Change root to the Linux install
  3. Mount additional (if any) partitions/drives
  4. Add exclusions
  5. Use the backup script to backup
Читайте также:  Linux как монтировать образ

To minimize downtime the backup can alternatively be performed on a running system using LVM snapshots, if all filesystems reside on LVM volumes.

Boot with LiveCD

Many Linux bootable CDs, USBs. have the ability to let you change root to your install. While changing root is not necessary to do a backup, it provides the ability to just run the script without need to transfer it to a temporary drive or having to locate it on the filesystem. The Live medium must be of the same architecture that your Linux install currently is (i.e. i686 or x86_64).

Changing root

First you should have a scripting environment set up on your current Linux install. If you do not know what that is, it means that you are able to execute any scripts that you may have as if they are regular programs. If you do not, see this article on how to do that. What you will need to do next is change root, to learn more about what changing root is, read this. When you change root, you do not need to mount any temporary file systems ( /proc , /sys , and /dev ). These temporary file systems get populated on boot and you actually do not want to backup them up because they can interfere with the normal (and necessary) population process which can change on any upgrade. To change root, you will need to mount your current Linux installs root partition. For example:

# mkdir /mnt/arch # mount /dev/your-partition-or-drive 

Use fdisk -l to discover you partitions and drives. Now chroot:

# cd /mnt/arch # chroot . /bin/bash

Warning: Do not use arch-chroot to chroot into the target system — the backup process will fail as it will try to back up temporary file systems, all system memory and other interesting things. Use plain chroot instead.

This example obviously uses bash but you can use other shells if available. Now you will be in your scripted environment (this is provided that you have your ~/.bashrc sourced on entry):

# If using bash, source the local .bashrc source ~/.bashrc

Mount other partitions

Other partitions that you use (if any) will need to be mounted in their proper places (e.g. if you have a separate /home partition).

Exclude file

tar has the ability to ignore specified files and directories. The syntax is one definition per line. tar also has the capability to understand regular expressions (regexps). For example:

# Not old backups /opt/backup/arch-full* # Not temporary files /tmp/* # Not the cache for pacman /var/cache/pacman/pkg/ .

Backup script

Backing up with bsdtar is straight-forward process. Here is a basic script that can do it and provides a couple checks. You will need to modify this script to define your backup location, and exclude file (if you have one), and then just run this command after you have chroot ed and mounted all your partitions. Note that GNU tar with —xattrs will not preserve extended attributes.

#!/bin/bash # full system backup # Backup destination backdest=/opt/backup # Labels for backup name #PC=$ pc=pavilion distro=arch type=full date=$(date "+%F") backupfile="$backdest/$distro-$type-$date.tar.gz" # Exclude file location prog=$ # Program name from filename excdir="/home//.bin/root/backup" exclude_file="$excdir/$prog-exc.txt" # Check if chrooted prompt. echo -n "First chroot from a LiveCD. Are you ready to backup? (y/n): " read executeback # Check if exclude file exists if [ ! -f $exclude_file ]; then echo -n "No exclude file exists, continue? (y/n): " read continue if [ $continue == "n" ]; then exit; fi fi if [ $executeback = "y" ]; then # -p, --acls and --xattrs store all permissions, ACLs and extended attributes. # Without both of these, many programs will stop working! # It is safe to remove the verbose (-v) flag. If you are using a # slow terminal, this can greatly speed up the backup process. # Use bsdtar because GNU tar will not preserve extended attributes. bsdtar --exclude-from=$exclude_file --acls --xattrs -cpvzf $backupfile / fi

Restoring

To restore from a previous backup, mount all relevant partitions, change the current working directory to the root directory, and execute

$ bsdtar --acls --xattrs -xpzf backupfile 

replacing backupfile with the backup archive. Removing all files that had been added since the backup was made must be done manually. Recreating the filesystem(s) is an easy way to do this.

Читайте также:  Linux restore after rm

Backup with parallel compression

To back up using parallel compression (SMP), use pbzip2 (Parallel bzip2):

# bsdtar -cvf /path/to/chosen/directory/etc-backup.tar.bz2 -I pbzip2 /etc

Store etc-backup.tar.bz2 on one or more offline media, such as a USB stick, external hard drive, or CD-R. Occasionally verify the integrity of the backup process by comparing original files and directories with their backups. Possibly maintain a list of hashes of the backed up files to make the comparison quicker.

Restore corrupted /etc files by extracting the etc-backup.tar.bz2 file in a temporary working directory, and copying over individual files and directories as needed. To restore the entire /etc directory with all its contents execute the following command as root:

# bsdtar -xvf etc-backup.tar.bz2 -C /

Источник

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