Creating backup in linux

Простые инкрементальные бэкапы в 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

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

Читайте также:  User groups linux command

Например строка /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

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

Источник

How to Backup Linux Filesystem Using dump Command

On a Linux operating system environment, mastering how to create and restore backups is a very important skill set. It is easier for well-versed Linux user to attain their data backup goals from the terminal environment without the need for a GUI-oriented application package.

The Linux dump utility is effective in creating filesystem backups on an availed storage device. However, the filesystem supported by this backup utility disregards the likes of ReiserFS and FAT.

Читайте также:  Linux get so dependencies

The dump command only supports ext4, ext3, and ext2 filesystem and incremental backups. Under incremental backup support, a Linux user can flexibly execute their backup operations on daily, weekly, or monthly time frames.

It makes it easy to decide when and how you want your backups done. You get to decide which files should be involved in the scheduled backup process. Therefore, a Linux user can only focus on backing up files with significant changes or the ones that were recently added to the targeted filesystem.

How to Install Dump Utility in Linux

If you do not have the dump utility installed on your Linux machine, you can install it by executing one of the following installation commands in regards to the Linux operating system distribution you are using.

$ sudo apt-get install dump [On Debian, Ubuntu and Mint] $ sudo yum install dump [On RHEL/CentOS/Fedora and Rocky Linux/AlmaLinux] $ sudo emerge -a sys-apps/dump [On Gentoo Linux] $ sudo pacman -S dump [On Arch Linux] $ sudo zypper install dump [On OpenSUSE]

Linux Dump Command Usage

Once you run the dump backup utility, it first examines your existing Linux filesystem files and points out the ones that are worthy of any backup effort. The dump command needs several parameters for it to execute successfully:

  • The targeted dump level.
  • The media to host the created filesystem backup.
  • The filesystem to backup.

The dump command also accommodates optional parameters pointing to:

  • Specific backup media size.
  • Next tape request method.
  • Times and status of filesystem dump recording.

A typical dump command string adheres to the following syntax:

$ sudo dump options arguments filesystem

The dump command options:

  • 0-9 – This range signifies available dump levels. 0 caters for full filesystem backup while a higher number like 9 only prioritizes the backup of modified filesystem files.
  • -B records – Highlights how many dump records should exist in a single volume.
  • -b kbperdump – Highlights the number of kilobytes within a single dumb record.
  • -h level – With this option, a nodump attribute is associated with your backup files.
  • -f file – Points to a file or device name that will accommodate the created dump.
  • -d destiny – Defines the needed tape density.
  • -n – Use to alert operator group users when something like a tape change is required by the dump operation.
  • -s feet: Specifies the dump tape length in feet.
  • -u – Creates a record of all successful backups under the file /etc/dumpdates.
  • -t date – Specifies the date and time values associated with incremental backups.
  • -W – This option references the /etc/fstab and /etc/dumpdates files and highlights filesystem files that need backup.
  • -w – Goes hand in hand with the W option and highlights specific/individual files that need backup.
Читайте также:  Linux mint local repository

How to Backup Linux System using Dump Command

To determine the files that need backup on your Linux system, you will run a command similar to the following:

List Linux Filesystem to Backup

To back up the above filesystem (/dev/sda5) to an external device like /dev/sdb5 (identified by running the command sudo fdisk -l ), I would implement a dump command similar to the following:

$ sudo dump 0uaf /dev/sdb5 /dev/sda5

Backup Linux Filesystem Using Dump Command

The dump command has the dump option 0 since it’s a first-time backup attempt.

If you need your backup compressed, you would run the above command in the following manner:

$ sudo dump 0ufz /dev/sdb5 /dev/sda5

The created backup will be compressed with the z library. The dump backup command updates the system user as it continues to execute:

Compressed Linux Filesystem Backup Using Dump Command

Backup Linux Home Directory

To back up the files from a specific filesystem directory like your Home directory:

$ sudo dump 0ufz /dev/sdb5 /home

To back up files to a remote machine named linuxshelltips or identified by an IP address and with the tape device named /dev/sdb5, we will use the rdump command.

$ sudo rdump 0uf linuxshelltips:/dev/sdb5 /home

Backing Up Data to a Regular File

Supposing we want to back up the home directory to an existing regular file called 10g.img, we would implement the needed command in the following manner:

$ sudo dump 0f /media/dnyce/4E6A2E2E6A2E136F/10g.img /home

Backup Linux Data to File

To create such a writable image file to hold your backup data, run the following command. Also, specify the size of this writable image file.

$ dd if=/dev/zero of=10g.img bs=1 count=0 seek=10G

Afterward, check the created backup file:

Check Backup File

The created .img file backup can now be written to a disk device of your choice with this command:

$ sudo dd if=10g.img of=/dev/sdb5 bs=1M

How to Restore Linux System using Dump Command

To fully restore the above-created backup, we would run a command similar to the following:

The restored files will be written on the current directory path of the active Linux system user.

To restore filesystem backups from a remote machine we will use the rrestore command:

$ sudo rrestore tf linuxshelltips:/dev/sdb5

With the dump command, you can easily achieve full and incremental backups of your Linux filesystem files. The restore command reverses or does the opposite of the dump command to successfully re-instate your filesystem backups.

To learn more about these two commands and their usage, run:

Источник

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