我用git的目的主要是為了數據的完整性,信息不丟失,雖然repository的代碼服務器和本地都會存一份,但有時候自己的小片段代碼很多(比如github的gist),不可能每天都用得到,需要定期的備份,以備不時之需(比如網絡斷開、服務器當機等因素)。
一、備份原理
通過某種方法獲取需要備份repository的名稱(比如靜態配置等),如果在指定目錄里面該repository存在(即文件夾存在), 進入文件夾,執行git pull操作; 如果不存在,執行git clone操作。
二、自建git服務器備份
git服務器ip:192.168.1.100
git賬戶:git
Repositories:/home/git/test1.git,/home/git/test2.git
正常訪問:
git clone git@192.168.1.100:test1.git
git clone git@192.168.1.100:test2.git
1、配置config文件
config配置如下:
Host host100 Hostname 192.168.1.100 User git IdentityFile C:/Users/admin/.ssh/id_rsa_gitBackup
這個不懂的可以參考這里:http://www.cnblogs.com/MikeZhang/archive/2012/11/27/gitWithSshKey_20121127.html
2、批量獲取
python代碼:
import os hostName = "host100" dirs = [ 'test1', 'test2' ] for dirName in dirs: print dirName," : ", if os.path.exists(dirName): #如果存在執行pull操作 strCmd = "cd %s && git pull && cd .." % dirName os.system(strCmd) else: #不存在則執行clone操作 strCmd = "git clone %s:%s.git " % (hostName,dirName) os.system(strCmd)
三、github備份
1、配置config文件
Host github Hostname github.com User git IdentityFile C:/Users/admin/.ssh/id_rsa_github Host gist Hostname gist.github.com User git IdentityFile C:/Users/admin/.ssh/id_rsa_github_gist
2、備份Repositories(以我的github為例)
(1)命令行訪問方式:
git clone github:mike-zhang/cppCallLua.git
(2)python腳本批量操作:
#for github import os hostName = "github" userName = "mike-zhang" repoNames = [ 'cppCallLua', 'testCodes' ] for repo in repoNames: print repo," : ", if os.path.exists(repo): strCmd = "cd %s && git pull && cd .." % repo os.system(strCmd) else: strCmd = "git clone %s:%s/%s.git " % (hostName,userName,repo) os.system(strCmd)
(3)運行效果
3、備份gist(以我的gist為例)
(1)命令行操作
git clone git@gist.github.com:4166192.git gist-4166192
(2)python腳本批量操作
這里以兩個gist例子:

#for gist import os hostName = "gist" userName = "mike-zhang" repoNames = [ '4166192', '4084385' ] for gist in repoNames: print gist," : ", if os.path.exists(gist): strCmd = "cd %s && git pull && cd .." % gist os.system(strCmd) else: strCmd = "git clone %s:%s.git " % (hostName,gist) os.system(strCmd)
(3)運行效果
我這里考慮的比較簡單,更強大的功能還需讀者自行擴展。
源碼地址(gist):https://gist.github.com/4166192
本文github地址:
https://github.com/mike-zhang/mikeBlogEssays/blob/master/2012/20121129_git批量備份.md
歡迎補充