#!/usr/bin/env python # coding=utf-8 # gitlab源码备份 import os import datetime import requests class GitlabBackup: def backup_projects(self): url = 'http://xxx.xxx.xxx.xxx/api/v3/projects/all?page=1&per_page=1000' headers = {'PRIVATE-TOKEN': 'xxxxxx'} result = requests.get(url, headers=headers, verify=False) json_obj = result.json() path = datetime.datetime.now().strftime('%Y%m%d-git-src') os.system("rm -rf " + path) os.system("mkdir " + path) for proj in json_obj: self.backup(proj, path) # clear data 1 month ago del_date = datetime.datetime.now() + datetime.timedelta(days=-32) del_path = del_date.strftime("%Y%m*") os.system("rm -rf " + del_path) def backup(self, proj, path): url = proj['http_url_to_repo'] dir = path + '/' + proj['path_with_namespace'] branch = proj['default_branch'] if branch is not None: print 'starting backup ------>' + dir + ',' + branch if os.path.exists(dir): os.system("rm -rf " + dir) os.system("git clone -b " + branch + " " + url.replace("http://", "http://xxx:xxx@") + " " + dir) if __name__ == '__main__': gitlab = GitlabBackup() gitlab.backup_projects()