一 背景
我自己有一些云服务器,上面有一些相对重要的文件目录,比如:通过picGo上传的一些照片目录,或者通过WebDAV同步到服务器上的一些文件目录。这些目录下的文件都相对重要,而自己的服务器磁盘并无定时备份等操作,一旦服务器故障,那么这些东西可能就会直接丢失。所以考虑通过Github来做备份,通过定时脚本把文件同步到Github上。
另外,Github仅适合用来备份一些小文件,单个仓库大小也是有限制的,一般单个文件超过50M有收到Github的告警,单个文件不能超过100M,单个仓库的大小建议控制在1G以内。如果不符合这些要求,那么可能不适合用Github来做备份,如果是小文件但是整体大于1G可以考虑拆分成多个目录备份成多个仓库。
二 具体操作与脚本
第一 在Github上创建私有仓库
这一步相信大家都知道怎么操作
第二 在服务器拉取Github仓库并把.git
目录复制到需要同步的目录下
假设服务器需要同步的目录为:/usr/share/nginx/html/imgs
1
2
3
4
5
6
7
8
9
10git clone git@github.com:xxxxxx/xxx.git
cd xxx
mv .git /usr/share/nginx/html/imgs/
cd /usr/share/nginx/html/imgs/
git init
git add .
git commit -am 'first commit'
git branch -M master
git push -u origin master
第三 编写定时同步脚本
具体脚本如下,如脚本位置: /root/script/sync_to_github.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
cd $1
has_push=false
untrack=`git status | grep 'Untracked files'`
if [ -n "$untrack" ]; then
git add .
has_push=true
fi
change_staged=`git status | grep 'Changes'`
if [ -n "$change_staged" ]; then
git commit -am 'auto commit ...'
has_push=true
fi
if [ "$has_push" = true ]; then
git push
fi
1 | chmod +x /root/script/sync_to_github.sh |
第四 通过Linux的crontab表达式定时执行同步
编辑crontab1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16# vim /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
0 3 * * * root /root/script/sync_to_github.sh /usr/share/nginx/html/imgs
重启crond服务1
2# 我的服务器是Centos7 其他服务器请自行百度重启crond服务的方法
systemctl restart crond