Nextcloud Backup Script

Inhalte [Ausblenden]

Wer eine Cloud(Nextcloud) besitzt, der muss sich auch um die Backups kümmern. Ich habe hier ein sehr verständliches Script, dass dir erlaub mithilfe eines Cronjobs regelmäßige Backups automatisiert zu machen. Das Script erkennt selbständig wie viele Backups gemacht worden sind und löscht ältere Backups.

Vorraussetzungen

  • Benutzer mit Root Rechten

Script/Code

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#!/bin/bash
#Backupverzeichnisse
nowDate=$(date +"%Y%m%d_%H%M%S")
backuppfd="/tmp/backup"
backupverz="${backuppfd}/${nowDate}/"
nextcloudfilesdir="/var/www/nextcloud"
maxBackups=3 # Anzahl an Backups
#Datenbank Benutzer und Passwort
nxtDatenbankname=""
nxtdbUser=""
nxtdbPassword=""
#Webserver
webservername="apache2" # Entweder per Apache2 oder Nginx
webserveruser="www-data" # Webserverusername; Default: www-data
filenamebkfile="backup-nextcloud-filedir.tar.gz" # Name des Backups der Dateien
filenamebkDb="nextcloud-db-backup.sql" # Name des Backups fuer die Datenbank
echoerror() {
cat <<< "$@" 1>&2;
exit 99;
}
ausgabe(){
echo $1
echo
}
if [ "$(id -u)" != "0" ]
then
echoerror "[E]: Das Script muss mit Root ausgefuehrt werden!"
fi
#Backupsverzeichnis vorhanden? Wenn nicht, erstellen
if [ ! -d "${backupverz}" ]
then
mkdir -p "${backupverz}"
fi
# Wartung in Nextcloud aktivieren
ausgabe "Wartung bei Nextcloud aktivieren..."
cd "${nextcloudfilesdir}"
sudo -u "${webserveruser}" php occ maintenance:mode --on
cd ~
ausgabe "Fertig"
# Webserver stoppen per Service
echo "Webserver stoppen..."
service "${webservername}" stop
ausgabe "Fertig"
# Backup der Dateien erstellen
ausgabe "Backup der NextCloud Dateien erstellen..."
tar -cpzf "${backupverz}/${filenamebkfile}" -C "${nextcloudfilesdir}" .
ausgabe "Fertig"
# Backup der Datenbank erstellen
ausgabe "Backup der Nextcloud Datenbank erstellen..."
mysqldump --single-transaction -h localhost -u "${nxtdbUser}" -p"${nxtdbPassword}" "${nxtDatenbankname}" > "${backupverz}/${filenamebkDb}"
ausgabe "Fertig"
# Webserver wieder per Service starten
ausgabe "Webserver starten..."
service "${webservername}" start
ausgabe "Fertig"
# Wartung in Nextcloud wieder deaktivieren
ausgabe "Wartung wieder deaktivieren..."
cd "${nextcloudfilesdir}"
sudo -u "${webserveruser}" php occ maintenance:mode --off
cd ~
ausgabe "Fertig"
# Loeschen von alten Backups. Je nach Einstellung in maxBackups
if (( ${maxBackups} != 0 ))
then
nrOfBackups=$(ls -l ${backuppfd} | grep -c ^d)
if (( ${nrOfBackups} > ${maxBackups} ))
then
ausgabe "Alte Backups entfernen"
ls -t ${backuppfd} | tail -$(( nrOfBackups - maxBackups )) | while read dirToRemove; do
ausgabe "${dirToRemove}"
rm -r ${backuppfd}/${dirToRemove}
ausgabe "Fertig"
done
fi
fi
ausgabe "Backup wurde erfolgreich erstellt! ->(${backupverz})"
exit 0;
#!/bin/bash #Backupverzeichnisse nowDate=$(date +"%Y%m%d_%H%M%S") backuppfd="/tmp/backup" backupverz="${backuppfd}/${nowDate}/" nextcloudfilesdir="/var/www/nextcloud" maxBackups=3 # Anzahl an Backups #Datenbank Benutzer und Passwort nxtDatenbankname="" nxtdbUser="" nxtdbPassword="" #Webserver webservername="apache2" # Entweder per Apache2 oder Nginx webserveruser="www-data" # Webserverusername; Default: www-data filenamebkfile="backup-nextcloud-filedir.tar.gz" # Name des Backups der Dateien filenamebkDb="nextcloud-db-backup.sql" # Name des Backups fuer die Datenbank echoerror() { cat <<< "$@" 1>&2; exit 99; } ausgabe(){ echo $1 echo } if [ "$(id -u)" != "0" ] then echoerror "[E]: Das Script muss mit Root ausgefuehrt werden!" fi #Backupsverzeichnis vorhanden? Wenn nicht, erstellen if [ ! -d "${backupverz}" ] then mkdir -p "${backupverz}" fi # Wartung in Nextcloud aktivieren ausgabe "Wartung bei Nextcloud aktivieren..." cd "${nextcloudfilesdir}" sudo -u "${webserveruser}" php occ maintenance:mode --on cd ~ ausgabe "Fertig" # Webserver stoppen per Service echo "Webserver stoppen..." service "${webservername}" stop ausgabe "Fertig" # Backup der Dateien erstellen ausgabe "Backup der NextCloud Dateien erstellen..." tar -cpzf "${backupverz}/${filenamebkfile}" -C "${nextcloudfilesdir}" . ausgabe "Fertig" # Backup der Datenbank erstellen ausgabe "Backup der Nextcloud Datenbank erstellen..." mysqldump --single-transaction -h localhost -u "${nxtdbUser}" -p"${nxtdbPassword}" "${nxtDatenbankname}" > "${backupverz}/${filenamebkDb}" ausgabe "Fertig" # Webserver wieder per Service starten ausgabe "Webserver starten..." service "${webservername}" start ausgabe "Fertig" # Wartung in Nextcloud wieder deaktivieren ausgabe "Wartung wieder deaktivieren..." cd "${nextcloudfilesdir}" sudo -u "${webserveruser}" php occ maintenance:mode --off cd ~ ausgabe "Fertig" # Loeschen von alten Backups. Je nach Einstellung in maxBackups if (( ${maxBackups} != 0 )) then nrOfBackups=$(ls -l ${backuppfd} | grep -c ^d) if (( ${nrOfBackups} > ${maxBackups} )) then ausgabe "Alte Backups entfernen" ls -t ${backuppfd} | tail -$(( nrOfBackups - maxBackups )) | while read dirToRemove; do ausgabe "${dirToRemove}" rm -r ${backuppfd}/${dirToRemove} ausgabe "Fertig" done fi fi ausgabe "Backup wurde erfolgreich erstellt! ->(${backupverz})" exit 0;
#!/bin/bash

#Backupverzeichnisse
nowDate=$(date +"%Y%m%d_%H%M%S")
backuppfd="/tmp/backup"
backupverz="${backuppfd}/${nowDate}/"
nextcloudfilesdir="/var/www/nextcloud"
maxBackups=3 # Anzahl an Backups

#Datenbank Benutzer und Passwort
nxtDatenbankname=""
nxtdbUser=""
nxtdbPassword=""

#Webserver
webservername="apache2" # Entweder per Apache2 oder Nginx 
webserveruser="www-data" # Webserverusername; Default: www-data
filenamebkfile="backup-nextcloud-filedir.tar.gz" # Name des Backups der Dateien
filenamebkDb="nextcloud-db-backup.sql" # Name des Backups fuer die Datenbank

echoerror() { 
	cat <<< "$@" 1>&2;
	exit 99; 
}
ausgabe(){
	echo $1
	echo
}

if [ "$(id -u)" != "0" ]
then
	echoerror "[E]: Das Script muss mit Root ausgefuehrt werden!"
fi

#Backupsverzeichnis vorhanden? Wenn nicht, erstellen
if [ ! -d "${backupverz}" ]
then
	mkdir -p "${backupverz}"
fi

# Wartung in Nextcloud aktivieren
ausgabe "Wartung bei Nextcloud aktivieren..."
cd "${nextcloudfilesdir}"
sudo -u "${webserveruser}" php occ maintenance:mode --on
cd ~
ausgabe "Fertig"

# Webserver stoppen per Service
echo "Webserver stoppen..."
service "${webservername}" stop
ausgabe "Fertig"

# Backup der Dateien erstellen
ausgabe "Backup der NextCloud Dateien erstellen..."
tar -cpzf "${backupverz}/${filenamebkfile}" -C "${nextcloudfilesdir}" .
ausgabe "Fertig"

# Backup der Datenbank erstellen
ausgabe "Backup der Nextcloud Datenbank erstellen..."
mysqldump --single-transaction -h localhost -u "${nxtdbUser}" -p"${nxtdbPassword}" "${nxtDatenbankname}" > "${backupverz}/${filenamebkDb}"
ausgabe "Fertig"

# Webserver wieder per Service starten
ausgabe "Webserver starten..."
service "${webservername}" start
ausgabe "Fertig"

# Wartung in Nextcloud wieder deaktivieren
ausgabe "Wartung wieder deaktivieren..."
cd "${nextcloudfilesdir}"
sudo -u "${webserveruser}" php occ maintenance:mode --off
cd ~
ausgabe "Fertig"

# Loeschen von alten Backups. Je nach Einstellung in maxBackups
if (( ${maxBackups} != 0 ))
then	
	nrOfBackups=$(ls -l ${backuppfd} | grep -c ^d)
	if (( ${nrOfBackups} > ${maxBackups} ))
	then
		ausgabe "Alte Backups entfernen"
		ls -t ${backuppfd} | tail -$(( nrOfBackups - maxBackups )) | while read dirToRemove; do
		ausgabe "${dirToRemove}"
		rm -r ${backuppfd}/${dirToRemove}
		ausgabe "Fertig"
    done
	fi
fi
ausgabe "Backup wurde erfolgreich erstellt! ->(${backupverz})"
exit 0;

Benutzung

Will man manuell ein Backup erstellen genügt es, das Script per Bash aufzurufen.

./NextCloudBackup.sh

Per Cron steuern

wir öffnen unter root die Cronshell auf:

crontab -e

und fügen eine Zeile hinzu:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
0 1 * * * /home/<pfadZumScript>/NextcloudBackup.sh >> /tmp/back_log.log 2>&1
# Edit this file to introduce tasks to be run by cron. # # Each task to run has to be defined through a single line # indicating with different fields when the task will be run # and what command to run for the task # # To define the time you can provide concrete values for # minute (m), hour (h), day of month (dom), month (mon), # and day of week (dow) or use '*' in these fields (for 'any').# # Notice that tasks will be started based on the cron's system # daemon's notion of time and timezones. # # Output of the crontab jobs (including errors) is sent through # email to the user the crontab file belongs to (unless redirected). # # For example, you can run a backup of all your user accounts # at 5 a.m every week with: # 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/ # # For more information see the manual pages of crontab(5) and cron(8) # # m h dom mon dow command 0 1 * * * /home/<pfadZumScript>/NextcloudBackup.sh >> /tmp/back_log.log 2>&1
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command

0 1 * * * /home/<pfadZumScript>/NextcloudBackup.sh >> /tmp/back_log.log 2>&1

Übersetzung: Jeder Nacht um 1Uhr wird das Script NextcloudBackup.sh aufgerufen. Erstelle eine Log Datei unter /tmp/.

Natürlich kann man das Script nach seinen eigenen Wünschen verändern. So kann man ein Upload zum Backup Servers implementieren oder eine E-mail Benachrichtigung erstellen.

Viel Spaß 🙂

Wie hilfreich war dieser Beitrag?

Klicke auf die Sterne um zu bewerten!

Durchschnittliche Bewertung 4.9 / 5. Anzahl Bewertungen: 9

Bisher keine Bewertungen! Sei der Erste, der diesen Beitrag bewertet.

4 Kommentare

  1. Hey Daniel, vielen Dank für die Vorlage.
    Im Script hat sich aber ein kleiner Tippfehler eingeschlichen. Schau mal bei dem Block „# Wartung in Nextcloud wieder deaktivieren“. Es wird so nicht funktionieren den Maintenance Mode wieder zu aktivieren da du mit „${webserverUser}“ arbeitest. Das klappt nicht, da die Variable „webserveruser“ keine Großbuchstaben enthält.

    Greets
    Julian

  2. Hallöchen, super praktisches Script, danke dafür.

    Bei mir wurde allerdings ein Fehler geworfen in Zeile 21 bei ausgabe(), hier ist ein leerer „echo“ Befehl, der einen Fehler verursacht. Ich habe einfach ein echo „—“ draus gemacht, dann hat man auch ein Trennzeichen bei der Ausführung.

    Ach und, falls jemand nach dem Datenbanknamen sucht: der ist bei MySQL-Nextclouds standardmäßig „nextcloud“

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert