Shell脚本-Gitlab代码库备份

何向荣
2023-12-01

Shell脚本—Gitlab代码库备份

应公司要求,需每月对代码库进行备份刻录光盘进行保存,故想到写一个自动备份的脚本,并通过邮件进行通知。
因公司gitlab代码库是通过docker进行启动,故备份需对代码库和docker镜像同步进行备份,备份脚本内容如下

#!/usr/bin/bash
## gitlab backup
## by shanhai
gitlab_docker_id=`docker ps | grep gitlab-ce | awk '{print $1}'`
gitlab_image_id=`docker images | grep gitlab-ce | awk '{print $3}'`

gitlab_backup(){
	docker exec -it $gitlab_docker_id gitlab-rake gitlab:backup:create
	find /home/gbase/app/gitlab/data/backups/ -name "*_13.2.6_gitlab_backup.tar"
	if [ $? -eq 0 ];then
		cp /home/gbase/app/gitlab/data/backups/*_13.2.6_gitlab_backup.tar /data/gitlab_backup
		cp /home/gbase/app/gitlab/config/gitlab.rb /data/gitlab_backup
		cp /home/gbase/app/gitlab/config/gitlab-secrets.json /data/gitlab_backup
	else
		echo "gitlab backup faild,Please check it"
		exit
	fi
}

images_backup(){
	cd /data/gitalb_backup
	docker save -o gitlab_image_backup_`date +%F`.tar.gz $gitlab_image_id
	find /data/gitlab_backup/ -name "gitalb_image_backup_`date +%F`.tar.gz" && find /data/gitlab_backup/ -name "*_13.2.6_gitlab_backup.tar"
	if [ $? -eq 0 ];then
		/usr/bin/python3 /home/gbase/app/gitlab_backup.py
	
	else
		echo "gitlab image backup faild,Please check it"
		exit
	fi
}

gitlab_backup
images_backup

邮件发送脚本如下

#!/usr/bin/env python3
import time
import sys
from datetime import datetime
import subprocess

time_start=time.time()
datetime.now()
current_tm=datetime.now().strftime('%Y%m%d%H%M')
today=datetime.now().strftime('%Y-%m-%d')

import smtplib
from socket import gaierror

port = 25
smtp_server = "10.0.0.99"
login = "**@**.com"
password = "****"

sender - "**@**,cin"
receiver_1 = "shanhai@**.com"
receiver_2 = "**@**.com"

message - f"""\
Subject: Gitlab Backup Norification E-Mail {today}
To: {receiver_1},{receiver_2}
From: {sender}
------------------------------------------------------------
The gitalb_package backup is successful

The path is \\10.0.0.1\data\gitlab_backup
------------------------------------------------------------
This is a message by scm_backup with Pythn."""

try:
	with smtplib.SMTP(smtp_server, port) as server:
		server.login(login, password)
		server.sendmail(sender, receiver_1, message)
		server.sendmail(sencer, receiver_2, message)
	
	print('Sent')
except (gaierror, ConnectionRefusecdError):
	print('Failed to connect to the server. Bad connection settings?')
except smtplib.SMTPServerDisconnected:
	print('Failed to connect to the server. Wrong user/password?')
except smtplib.SMTPException as e:
	print('SMTP error occurred: ' + str(e))

计划任务如下

0 6 25 * *	/bin/sh	/home/gbase/app/gitlab_backup.sh
 类似资料: