Come eseguire il backup utilizzando Duplicity su Ubuntu 16.04

Duplicity è un’applicazione software che fornisce volumi di backup tar crittografati, firmati digitalmente e versionati che possono essere caricati su un file server remoto o locale. È supportato in tutte le principali distribuzioni Linux come Ubuntu, Linux Mint, Debian, Fedora e altre. Duplicity supporta la sincronizzazione di file locale o remota tra file system o server utilizzando SSH/SCP, Rsync, FTP, WebDAV, ecc.
In questo tutorial, spiegherò come impostare la duplicità e usarla per automatizzare in modo sicuro i backup sul tuo server Ubuntu.
Prerequisiti
Dobbiamo installare tutti i pacchetti predefiniti per Ubuntu dai repository.
$apt-get update
$apt-get install ncftp python-paramiko python-pycryptopp lftp python-boto python-dev librsync-dev
Installa Duplicità
Possiamo installare duplicity dai pacchetti del repository semplicemente eseguendo questo comando.
$ apt install duplicity
Confermiamo la versione duplicata dopo l’installazione.
$ duplicity -V
duplicity 0.7.06
Crea chiavi SSH e GPG
Successivamente, dovremo utilizzare le chiavi SSH per autenticarci in modo sicuro con il sistema remoto senza dover fornire una password. Utilizziamo anche chiavi GPG per crittografare i dati prima di trasferirli nella posizione di backup. Queste chiavi garantiscono un’interazione sicura tra i server.
Generiamo una chiave SSH crittografata RSA a 2048 bit dal nostro utente root per abilitare l’accesso senza password alla macchina di backup.
$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:gxdDFAjm6AUSi7LzczlDE1orygCzplmjQCqBFkxJ8Dc root@duplicity-01
The key's randomart image is:
+---[RSA 2048]----+
|O=o o. o+. |
|o*.= .. |
|Ooo E o |
|** = + . o |
|O.* + . S |
|BB + o . . |
|=.o = |
| o o |
| |
+----[SHA256]-----+
Ora copiamo questa chiave RSA nella nostra posizione di backup remota.
$ssh-copy-id root@45.55.165.191
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '45.55.165.191 (45.55.165.191)' can't be established.
ECDSA key fingerprint is SHA256:XhFoQ3/mIsjGH7RfMwH6m0MHbj1B1kR4Sug5vfTQLdU.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@45.55.165.191's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@45.55.165.191'"
and check to make sure that only the key(s) you wanted were added.
Pertanto, possiamo accedere al server di backup da remoto senza fornire password dall’host. Dobbiamo creare un percorso di destinazione per salvare i backup. Ho creato una cartella Duplicity sul mio server di backup remoto.
$mkdir -p remotebackup/Duplicity
Il nostro prossimo passo è creare le chiavi GPG. Le chiavi GPG vengono utilizzate per una maggiore sicurezza e crittografia dei dati trasferiti ai server. Basta crearlo eseguendo questo comando di seguito:
$gpg --gen-key
Questo comando creerà le chiavi GPG e le salverà nella cartella /root/.gnupg/. Questa generazione di chiavi è interattiva e durante il processo dobbiamo selezionare e rispondere a varie domande.
$ gpg --gen-key
gpg (GnuPG) 1.4.20; Copyright (C) 2015 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Please select what kind of key you want:
(1) RSA and RSA (default)
(2) DSA and Elgamal
(3) DSA (sign only)
(4) RSA (sign only)
Your selection?
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048)
Requested keysize is 2048 bits
Please specify how long the key should be valid.
0 = key does not expire
<n> = key expires in n days
<n>w = key expires in n weeks
<n>m = key expires in n months
<n>y = key expires in n years
Key is valid for? (0)
Key does not expire at all
Is this correct? (y/N) y
You need a user ID to identify your key; the software constructs the user ID
from the Real Name, Comment and Email Address in this form:
"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>"
Real name: Saheetha
Email address: saheetha1@gmail.com
Comment:
You selected this USER-ID:
"Saheetha <saheetha1@gmail.com>"
Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
You need a Passphrase to protect your secret key.
gpg: gpg-agent is not available in this session
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
Not enough random bytes available. Please do some other work to give
the OS a chance to collect more entropy! (Need 287 more bytes)
A questo punto, ti viene chiesto di generare entropia. L’entropia è fondamentalmente l’imprevedibilità nel tuo sistema. Il tuo VPS ha bisogno di entropia per creare una chiave che sia effettivamente casuale. Se ricevi questo messaggio come evidenziato, devi installare haveged
package per creare una chiave casuale e riprovare il comando.
$apt-get install haveged
Questo pacchetto può essere installato dal repository predefinito. Dopo l’installazione, è necessario assicurarsi che la seguente impostazione sia aggiornata come di seguito nel suo file di configurazione /etc/default/haveged.
DAEMON_ARGS="-w 1024"
Infine, assicurati che sia impostato per l’avvio all’avvio:
$update-rc.d haveged defaults
Dopo averlo impostato, puoi riavviare gpg --gen-key
comando ancora una volta e completare il processo con quanto segue.
$ gpg --gen-key
gpg (GnuPG) 1.4.20; Copyright (C) 2015 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Please select what kind of key you want:
(1) RSA and RSA (default)
(2) DSA and Elgamal
(3) DSA (sign only)
(4) RSA (sign only)
Your selection?
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048)
Requested keysize is 2048 bits
Please specify how long the key should be valid.
0 = key does not expire
<n> = key expires in n days
<n>w = key expires in n weeks
<n>m = key expires in n months
<n>y = key expires in n years
Key is valid for? (0)
Key does not expire at all
Is this correct? (y/N)
Key is valid for? (0)
Key does not expire at all
Is this correct? (y/N) y
You need a user ID to identify your key; the software constructs the user ID
from the Real Name, Comment and Email Address in this form:
"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>"
Real name: Saheetha
Email address: yourname@gmail.com
Comment:
You selected this USER-ID:
"Saheetha <saheetha1@gmail.com>"
Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
You need a Passphrase to protect your secret key.
gpg: gpg-agent is not available in this session
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
+++++
...+++++
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
.................+++++
........+++++
gpg: /root/.gnupg/trustdb.gpg: trustdb created
gpg: key F03B3360 marked as ultimately trusted
public and secret key created and signed.
gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0 valid: 1 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 1u
pub 2048R/F03B3360 2016-11-25
Key fingerprint = F262 785A B5E6 25E9 56E7 4484 3354 43D9 F03B 3360
uid Saheetha <yourname@gmail.com>
sub 2048R/C4D85223 2016-11-25
Puoi anche ottenere informazioni sulla tua chiave gpg eseguendo questo comando.
$ gpg --list-keys
/root/.gnupg/pubring.gpg
------------------------
pub 2048R/F03B3360 2016-11-25
uid Saheetha <yourname@gmail.com>
sub 2048R/C4D85223 2016-11-25
Come usare la duplicità
Eseguiamo un test iniziale del nostro sistema di duplicazione creando una cartella di file fittizia di cui eseguire il backup. È possibile creare una cartella di prova e creare alcuni file per il backup.
$ mkdir Test-DoC
$ cd Test-DoC
$ touch file{1..100}
Ora puoi eseguire questo comando per eseguire il backup sul nostro server di backup remoto.
$root@duplicity-01:~# duplicity /root/Test-DoC/ sftp://root@45.55.165.191//remotebackup/Duplicity
The authenticity of host '45.55.165.191' can't be established.
SSH-RSA key fingerprint is 20:9d:3b:fe:af:df:d1:40:5d:bc:f4:2c:6e:30:54:e0.
Are you sure you want to continue connecting (yes/no)? yes
Local and Remote metadata are synchronized, no sync needed.
Last full backup date: none
GnuPG passphrase for decryption:
Retype passphrase for decryption to confirm:
No signatures found, switching to full backup.
--------------[ Backup Statistics ]--------------
StartTime 1480059313.48 (Fri Nov 25 07:35:13 2016)
EndTime 1480059313.53 (Fri Nov 25 07:35:13 2016)
ElapsedTime 0.05 (0.05 seconds)
SourceFiles 101
SourceFileSize 4096 (4.00 KB)
NewFiles 101
NewFileSize 4096 (4.00 KB)
DeletedFiles 0
ChangedFiles 0
ChangedFileSize 0 (0 bytes)
ChangedDeltaSize 0 (0 bytes)
DeltaEntries 101
RawDeltaSize 0 (0 bytes)
TotalDestinationSizeChange 1029 (1.00 KB)
Errors 0
-------------------------------------------------
Puoi confermare il backup collegandoti al nostro server remoto.
root@duplicity-02:/remotebackup/Duplicity# ll
total 20
drwxr-xr-x 2 root root 4096 Nov 25 07:35 ./
drwxr-xr-x 3 root root 4096 Nov 25 07:11 ../
-rw-r--r-- 1 root root 438 Nov 25 07:35 duplicity-full.20161125T073505Z.manifest.gpg
-rw-r--r-- 1 root root 1029 Nov 25 07:35 duplicity-full.20161125T073505Z.vol1.difftar.gpg
-rw-r--r-- 1 root root 1596 Nov 25 07:35 duplicity-full-signatures.20161125T073505Z.sigtar.gpg
Questi file dovrebbero contenere le informazioni di backup. Poiché si tratta solo di testare i file, possiamo rimuovere tutti i file.
Backup dell’intero server
Creiamo il primo backup del server. Eseguiamo il backup dell’intero root server, escludendo alcune cartelle come /proc, /sys e /tmp. Qui, dobbiamo utilizzare la chiave pub GPG generata in precedenza e Paraphrase per proteggere e crittografare i nostri dati. Questa è la sintassi generale per la creazione del backup.
duplicity --encrypt-key Pub-key_from_GPG --exclude files_to_exclude --include files_to_include path_to_back_up sftp://root@remotebackupHostname//remotebackup/duplicity
Ho eseguito questo comando per eseguire il backup del mio server.
root@duplicity-01:~# PASSPHRASE="docker" duplicity --encrypt-key F03B3360 --exclude /proc --exclude /sys --exclude /tmp / sftp://root@45.55.165.191//remotebackup/Duplicity/
Local and Remote metadata are synchronized, no sync needed.
Last full backup date: none
No signatures found, switching to full backup.
--------------[ Backup Statistics ]--------------
StartTime 1480143194.50 (Sat Nov 26 06:53:14 2016)
EndTime 1480143304.84 (Sat Nov 26 06:55:04 2016)
ElapsedTime 110.34 (1 minute 50.34 seconds)
SourceFiles 69101
SourceFileSize 885736795 (845 MB)
NewFiles 69101
NewFileSize 885736795 (845 MB)
DeletedFiles 0
ChangedFiles 0
ChangedFileSize 0 (0 bytes)
ChangedDeltaSize 0 (0 bytes)
DeltaEntries 69101
RawDeltaSize 847552198 (808 MB)
TotalDestinationSizeChange 345904578 (330 MB)
Errors 0
-------------------------------------------------
Ci vorrà del tempo per completare questo processo di backup. Poiché questa è la prima volta che eseguiamo il backup, la duplicità creerà un backup completo. La deduplicazione divide blocchi di dati in volumi per semplificare i trasferimenti di file.
root@duplicity-02:/remotebackup/Duplicity# ll
total 354864
drwxr-xr-x 2 root root 4096 Nov 26 06:55 ./
drwxr-xr-x 3 root root 4096 Nov 25 07:11 ../
-rw-r--r-- 1 root root 303666 Nov 26 06:55 duplicity-full.20161126T065314Z.manifest.gpg
-rw-r--r-- 1 root root 26241374 Nov 26 06:54 duplicity-full.20161126T065314Z.vol10.difftar.gpg
-rw-r--r-- 1 root root 26192752 Nov 26 06:54 duplicity-full.20161126T065314Z.vol11.difftar.gpg
-rw-r--r-- 1 root root 26206134 Nov 26 06:54 duplicity-full.20161126T065314Z.vol12.difftar.gpg
-rw-r--r-- 1 root root 26196266 Nov 26 06:54 duplicity-full.20161126T065314Z.vol13.difftar.gpg
-rw-r--r-- 1 root root 4999361 Nov 26 06:55 duplicity-full.20161126T065314Z.vol14.difftar.gpg
-rw-r--r-- 1 root root 26256306 Nov 26 06:53 duplicity-full.20161126T065314Z.vol1.difftar.gpg
-rw-r--r-- 1 root root 26216804 Nov 26 06:53 duplicity-full.20161126T065314Z.vol2.difftar.gpg
-rw-r--r-- 1 root root 26198345 Nov 26 06:53 duplicity-full.20161126T065314Z.vol3.difftar.gpg
-rw-r--r-- 1 root root 26197666 Nov 26 06:53 duplicity-full.20161126T065314Z.vol4.difftar.gpg
-rw-r--r-- 1 root root 26237799 Nov 26 06:53 duplicity-full.20161126T065314Z.vol5.difftar.gpg
-rw-r--r-- 1 root root 26218126 Nov 26 06:53 duplicity-full.20161126T065314Z.vol6.difftar.gpg
-rw-r--r-- 1 root root 26252966 Nov 26 06:53 duplicity-full.20161126T065314Z.vol7.difftar.gpg
-rw-r--r-- 1 root root 26234136 Nov 26 06:54 duplicity-full.20161126T065314Z.vol8.difftar.gpg
-rw-r--r-- 1 root root 26256543 Nov 26 06:54 duplicity-full.20161126T065314Z.vol9.difftar.gpg
-rw-r--r-- 1 root root 17136137 Nov 26 06:55 duplicity-full-signatures.20161126T065314Z.sigtar.gpg
Con una nuova consegna, la mia configurazione ha creato 15 volumi che sono stati trasferiti al sistema remoto. Poiché abbiamo un backup completo per il mio server sul nostro server di backup, il backup successivo sarà un backup incrementale. Sono più veloci e richiedono meno tempo per il trasferimento dei dati. Puoi persino forzare un altro backup completo semplicemente eseguendo questo comando.
$PASSPHRASE="docker" duplicity full --encrypt-key F03B3360 --exclude /proc --exclude /sys --exclude /tmp / sftp://root@45.55.165.191//remotebackup/Duplicity/
Pianificazione dei backup
Ora possiamo imparare come programmare i nostri backup giornalieri o settimanali impostando lo script di backup in modo che venga eseguito automaticamente. Innanzitutto, creiamo un file passphrase nella nostra cartella /root per passare automaticamente la passphrase senza una richiesta interattiva per la parafrasi.
$cat /root/.passphrase
PASSPHRASE="docker"
Proteggi i permessi dei file e limitali a 600.
Vediamo come creare backup giornalieri. Dobbiamo creare il nostro script di backup nella cartella /etc/cron.daily. Tutti i cron job impostati in questa cartella verranno eseguiti giornalmente.
$:/etc/cron.daily# cat duplicity.inc
#!/bin/sh
test -x $(which duplicity) || exit 0
. /root/.passphrase
export PASSPHRASE
$(which duplicity) --encrypt-key F03B3360 --exclude /proc --exclude /sys --exclude /tmp --exclude /var / sftp://root@45.55.165.191//remotebackup/Duplicity/
Assicurati di concedere l’autorizzazione eseguibile per lo script.
$:/etc/cron.daily# chmod +x duplicity.inc
Possiamo eseguire questo script per assicurarci che tutto funzioni correttamente.
root@duplicity-01:/etc/cron.daily# ./duplicity.inc
Local and Remote metadata are synchronized, no sync needed.
Last full backup date: Sat Nov 26 06:53:14 2016
--------------[ Backup Statistics ]--------------
StartTime 1480564726.91 (Thu Dec 1 03:58:46 2016)
EndTime 1480564748.83 (Thu Dec 1 03:59:08 2016)
ElapsedTime 21.91 (21.91 seconds)
SourceFiles 69108
SourceFileSize 899520535 (858 MB)
NewFiles 32
NewFileSize 20761841 (19.8 MB)
DeletedFiles 13
ChangedFiles 9
ChangedFileSize 2779 (2.71 KB)
ChangedDeltaSize 0 (0 bytes)
DeltaEntries 54
RawDeltaSize 20737072 (19.8 MB)
TotalDestinationSizeChange 17502790 (16.7 MB)
Errors 0
-------------------------------------------------
Allo stesso modo, possiamo pianificare un backup per forzare un backup completo settimanale e mantenerlo. Perché i backup incrementali diventeranno sempre più difficili man mano che le modifiche si accumulano. Verranno configurati backup completi settimanali per aggiornare il database.
Facciamolo creando uno script di backup completamente duplicato nella cartella /etc/cron.weekly. È possibile creare uno script duplicity.full in questa directory.
$:/etc/cron.weekly# chmod +x duplicity.full
$:/etc/cron.weekly# cat duplicity.full
#!/bin/sh
test -x $(which duplicity) || exit 0
. /root/.passphrase
export PASSPHRASE
$(which duplicity) full --encrypt-key F03B3360 --exclude /proc --exclude /sys --exclude /tmp --exclude /var / sftp://root@45.55.165.191//remotebackup/Duplicity/
Possiamo anche aggiungere questo comando al nostro script duplicity.full per ripulire i vecchi file di backup. Aggiungi questo comando per mantenere solo tre backup e i corrispondenti backup incrementali.
$(which duplicity) remove-all-but-n-full 3 --force sftp://root@45.55.165.191//remotebackup/Duplicity/
Pertanto, il nostro script settimanale creerà un backup completo del nostro server e rimuoverà tutti i vecchi file di backup indesiderati dal server. Possiamo eseguire manualmente il nostro script per testarne la funzionalità.
$:/etc/cron.weekly# ./duplicity.full
Local and Remote metadata are synchronized, no sync needed.
Last full backup date: Sat Nov 26 06:53:14 2016
--------------[ Backup Statistics ]--------------
StartTime 1480570674.29 (Thu Dec 1 05:37:54 2016)
EndTime 1480570791.54 (Thu Dec 1 05:39:51 2016)
ElapsedTime 117.26 (1 minute 57.26 seconds)
SourceFiles 69109
SourceFileSize 906577560 (865 MB)
NewFiles 69109
NewFileSize 906577560 (865 MB)
DeletedFiles 0
ChangedFiles 0
ChangedFileSize 0 (0 bytes)
ChangedDeltaSize 0 (0 bytes)
DeltaEntries 69109
RawDeltaSize 868388867 (828 MB)
TotalDestinationSizeChange 363488138 (347 MB)
Errors 0
-------------------------------------------------
Local and Remote metadata are synchronized, no sync needed.
Last full backup date: Thu Dec 1 05:37:53 2016
No old backup sets found, nothing deleted.
Conclusione
Congratulazioni! Abbiamo la nostra soluzione di backup automatizzata completamente operativa pronta per l’uso. Uno dei principali vantaggi di Duplicity rispetto ad altre soluzioni di backup è che crittografa i dati utilizzando la chiave GnuPG. Forniscono anche una soluzione di backup automatizzata che è ottima e può essere eseguita utilizzando semplici lavori cron. Spero che questo articolo ti sia stato utile! Si prega di pubblicare i vostri preziosi commenti e suggerimenti al riguardo.