My Raspberry Pi has many little applications and it happend already 2 times that the microsd was not working anymore. Therefore I decided to automate a weekly backup for my NAS.
To get the job done. First you have to mount your NAS towards your Raspberry Pi.
- Make a mount towards the NAS
Create the folder /mnt/backup
- Edit the the fstab file
sudo nano /etc/fstab
- In my case it looks liket this
//192.168.100.2/folder/on-your-nas /mnt/backup cifs iocharset=utf8,uid=1001,gid=1001,x-systemd.automount,x-systemd.requires=network-online.target,vers=1.0,credentials=/home/user/.ds414-pi-backup.creds
- create a file for the credentials
nano ~/.ds414-pi-backup.credsYou might want to set chmod / chown permission to ensure nobody else can check your .creds file.
- It should look like this
- To make your changes in the fstab effect type
sudo mount -a
Test your shared drive. You might want to re-start to check if the mount works fully automatically.
- Put the file in the desired location. I have it in /mnt/backup
- Make the script executable
chmod +x /mnt/backup/bkup_rpimage.sh
- Test the script. I run it with the following command
sudo ./bkup_rpimage.sh start -L backup-$(date +%Y-%m-%d).log -czd /mnt/backup/$(uname -n)-$(date +%Y-%m-%d).img
- Create a file calling the bkup_rpimage.sh with the correct variables
nano /mnt/backup/backup_pi.shThe following content
#!/bin/bash SHELL=/bin/bash PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games . /mnt/backup/bkup_rpimage.sh start -czdl /mnt/backup/$(uname -n)-$(date +%Y-%m-%d).img
chmod +x /mnt/backup/backup_pi.shThis will create a backup file, gzip it and removing the unzipped version once finished. Furthermore, it will ad a log file into the folder. The PATH part has to be adjusted to your needs.
Pay attention to change the PATH variable to your needs. You can find out more about your PATH by just typing
env, or you use
echo $PATH. Be aware that the cronjob is running with the user of the crontab. In this szenario I decided for root as the script needs multiple permissions only root has.
Therefore, the PATH has to be set correctly.
- Create a cronjob in order to automate the backup
sudo crontab -e
- Add the following line at the end of the crontab file
0 3 * * 1 /mnt/backup/backup_pi.shThis will create a cronjob running every week at 3 a.m
In order to test the script you can also change the cronjob to be executed each minute. Just type * * * * * instead of 0 3 * * * * within the crontab.
In order to see the currently running cronjobs:
ps fauxww | grep -A 1 '[C]RON'
# Then use
Sudo kill PID
To see the furhter logging details:
sudo tail /var/log/syslog
Restore of the Backup:
In order to restore the backup on a new sd card I just used the following program:
You just have to select “custom img” and select the previously unzipped gz file.