【36】树莓派自动备份

如果不做魔改的话,树莓派的系统是运行在一张 SD 卡上的。众所周知,SD 卡的耐用程度是非常差劲,用来运行操作系统这样大量读写的任务对数据安全是相当大的威胁。因此,给树莓派进行定期的全盘备份是一个很必要的事情了。

由于把树莓派当作 NAS 而外接了一块硬盘,因此这块硬盘自然成为了备份存储的位置。核心思想就是使用 dd 指令直接把整个 SD 卡的内容拷贝到一个镜像文件中。参考了以下两个项目/帖子,完成了我的备份脚本。

Using dd to backup a PI SD - Raspberry Pi Forums

kallsbo/BASH-RaspberryPI-System-Backup: Bash script for automatic imaging backup of a raspberry pi system while it’s running

代码如下。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/bin/bash
#
# Automate Raspberry Pi Backups
# https://github.com/kallsbo/BASH-RaspberryPI-System-Backup
# https://www.raspberrypi.org/forums/viewtopic.php?t=46911
#
# Usage: system_backup.sh {path} {days of retention}
#
# Below you can set the default values if no command line args are sent.
# The script will name the backup files {$HOSTNAME}.{YYYYmmdd}.img.gz
# When the script deletes backups older then the specified retention
# it will only delete files with it's own $HOSTNAME.

# Redirect output
exec >> /path/to/logfile/backup.log
exec 2>&1

echo "=============== Start Raspi Backup ==============="
echo $(date "+%Y-%m-%d %H:%M:%S") UTC
echo

# Declare vars and set standard values
backup_path=/path/to/backup/folder
retention_days=30

# Check that we are root!
if [[ ! $(whoami) =~ "root" ]]; then
echo ""
echo "**********************************"
echo "*** This needs to run as root! ***"
echo "**********************************"
echo ""
exit
fi

# Check to see if we got command line args
if [ ! -z $1 ]; then
   backup_path=$1
fi

if [ ! -z $2 ]; then
   retention_days=$2
fi

# Create trigger to force file system consistency check if image is restored
touch /boot/forcefsck

# Perform backup
dd bs=4M if=/dev/mmcblk0 | gzip > $backup_path/$HOSTNAME.$(date +%Y%m%d).img.gz
# Restore
# gzip -dc $backup_path/$HOSTNAME.{YYYYmmdd}.img.gz | dd bs=4M of=/dev/mmcblk0

# Remove fsck trigger
rm /boot/forcefsck

# Delete old backups
find $backup_path/$HOSTNAME.*.img.gz -mtime +$retention_days -type f -delete

echo
echo $(date "+%Y-%m-%d %H:%M:%S") UTC
echo "=================== Finished ====================="
echo

创建脚本后,可以把它加入 Crontab 定时运行备份。

由于需要用 root 权限运行脚本,因此使用 sudo crontab -e 添加 root 用户的运行任务:

1
30 4 * * 5 /home/pi/utils/backup.sh

这样它就会在每周五凌晨 4:30 自动进行 SD 卡全盘备份啦!


本文阅读量
本站访客量