restic 自动备份 linux

linux 全盘备份

环境: deepin 15
备份到: google drive
所用到的工具: restic, rclone, crontab, ssmtp

一、 编写脚本

  1. /restic_cron.sh
#!/bin/bash

if [ "$1" = "" ];then
	echo 'Wrong use of this sh. $argv0 <function>'
	echo 'function: backup , success_mail, fail_mail, run_backup'
	exit 1;
fi

echo $1

FUNC=$1

backup(){
	http_proxy=http://127.0.0.1:1082 curl ip.gs
	# /bin/bash  /restic_cron.sh success_mail
	# http_proxy=http://127.0.0.1:1082 
	http_proxy=http://127.0.0.1:1082 /usr/local/bin/restic -r rclone:k:/restic backup --verbose / --exclude-file=/excludes.txt
}

success_mail(){
	echo 'backup success.'&& echo 'Subject: BackUp Success. Machine: deepin@dell Time:'`date` | /usr/sbin/ssmtp *@qq.com;
}

fail_mail(){
	echo 'backup failed' && echo 'Subject: BackUp Fail!!!  Machine: deepin@dell Time:'`date` | /usr/sbin/ssmtp *@qq.com
}

run_backup(){
	echo 'backup is runing...'
	/expect.sh && success_mail || fail_mail
	echo 'backup finished...'
}



if [ "$FUNC" == "backup" ]; then
  backup
elif [ "$FUNC" == "success_mail" ]; then
  success_mail
elif [ "$FUNC" == "fail_mail" ]; then
  fail_mail
elif [ "$FUNC" == "run_backup" ]; then
  run_backup
fi

  1. /expect.sh

restic 的 repo 都有密码, 使用 expect 就无需输入密码, 达到自动备份的目的


#!/usr/bin/expect -f
set timeout -1
spawn /restic_cron.sh backup

expect {
	"enter password for repository:"
		{send -- "yourpassword\r"}

	"Fatal: *"
		{send_error "expect_error 1\n"; exit 1 }
	"snapshot * saved"
		{send_error "expect_error 1\n"; exit 0}
}

expect eof

二、 excludes.txt

用于指定那些目录不进行备份, 类似于 .gitignore

/dev/*
/proc/*
/sys/*
/media/*
/mnt/*
/tmp/*
/run/*
/var/run/*
/var/lock/*
/var/lib/docker/*
/var/lib/schroot/*
/lost+found
/timeshift/*
/timeshift-btrfs/*
/data/*
/DATA/*
/cdrom/*
/sdcard/*
/system/*
/etc/timeshift.json
/var/log/*
/swapfile
/snap/*
/root/.thumbanils
/root/.cache
/root/.gvfs
/root/.local/share/[Tt]rash
/home/*/.thumbnails
/home/*/.cache
/home/*/.dbus
/home/*/.gvfs
/home/*/.local/share/[Tt]rash
/root/.mozilla/firefox/*.default/Cache
/root/.mozilla/firefox/*.default/OfflineCache
/root/.opera/cache
/home/*/.mozilla/firefox/*.default/Cache
/home/*/.mozilla/firefox/*.default/OfflineCache
/home/*/.opera/cache
/var/cache/*
/**/vendor
/**/node_modules
/**/Cache
/**/Temp
/tmp-docker-pv/*
/home/david/Documents/WeChat Files/*

三、 crontab 设置

使用 root 的 crontab 以免因为权限问题导致错误

0 12 * * * /bin/bash /restic_cron.sh run_backup

四、 脚本关系

  • restic_cron.sh 调用 expect.sh 进行备份
  • expect.sh 调用具体的命令 restic, 成功与失败都将调用提前设置好的 ssmtp 命令用于发送邮件
    • ssmtp 命令就不做介绍了,就是辅助发邮件用的
  • restic 使用的 excludes.txt 决定了哪些文件不进行备份
    • restic 调用了 rclone 命令,前面文章有提到过,不再赘述; 有需求可以翻阅官方文档

五、 小结

  • 建议使用mac
  • 建议使用成熟的桌面版工具, 命令行版容易忽漏
  • 不要买 QLC 颗粒的 SSD
  • 不要买 QLC 颗粒的 SSD
  • 不要买 QLC 颗粒的 SSD
posted @ 2020-03-24 17:53  GETTOLIVE  阅读(564)  评论(0编辑  收藏  举报