linux的svn备份脚本
2020-05-12 本文已影响0人
牙齿不帅
需求:一个星期一次全备份,每天进行增量备份,备份文件远程传送到另一个文件服务器上,每天以邮件发送备份log。
脚本1:遍历多个版本库的备份脚本。
#svnbak.sh
#svn库名
proList=`cat svnlist.txt`
echo `date`
date=`date "+%Y-%m-%d"`
for name in $proList;
do
echo $name
#调用备份脚本2
./bak.sh $name >> $date-log
done
#发送邮件
python3.7 ./Smtp.py $date-log
脚本2:版本库的备份。
# bak.sh
#echo `date`
set -x
#远程备份服务器的ip
remoteIp="10.10.94.44"
PRONAME=$1
if test -z $PRONAME
then
echo "error proname is empty"
exit 1
fi
#备份目录,脚本所在的目录,远程备份服务器也有此目录
SVNBAK=/home/svnbak
BAKDIR=$SVNBAK/$PRONAME
if [ ! -d "$BAKDIR" ]
then
mkdir $BAKDIR
fi
#svn库所在目录
SVNDIR="/home/svn"
SVNPRO="$SVNDIR/$PRONAME"
echo $SVNPRO
date=`date "+%Y-%m-%d"`
week=`date "+%w"`
#发送文件到远程服务器,成功后删除文件
sendFile(){
svnlook youngest $SVNPRO > $BAKDIR/lastVersion.txt
file=$1
if [ -s "$file" ];then
#发送到远程服务器备份
du -sh $file
scp -r $file root@$remoteIp:$SVNBAK/$PRONAME-${file##*/}
if [ $? -eq 0 ]; then
echo "svn远程备份成功!"
rm -rf $file
else
echo "Sending $file to remote is failed!"
fi
fi
}
#全备份
if [ $week = "2" ]
then
file=$BAKDIR/svn_all.gz
echo $file
svnadmin dump $SVNPRO | gzip > $file
if [ -s "$file" ];then
sendFile $file
fi
exit 1
fi
#走增量备份
lastVersion=`cat $BAKDIR/lastVersion.txt`
let lastVersion=$lastVersion+1
echo "lastVersion:$lastVersion"
svnlook youngest $SVNPRO > $BAKDIR/nextVersion.txt
nextVersion=`cat $BAKDIR/nextVersion.txt`
echo "nextVersion:$nextVersion"
increFile=$BAKDIR/svn_increment_$lastVersion-$nextVersion-.gz
if [ $nextVersion -le $lastVersion ];then
echo "无新的版本号更新"
exit 1
fi
svnadmin dump --incremental -r $lastVersion:$nextVersion $SVNPRO | gzip > $increFile
if [ $? -ne 0 ];then
exit 1
fi
sendFile $increFile
Python发送邮件脚本。注意:需要安装python3以上版本。
#Smpt.py
import os
import smtplib
import sys
from email.mime.text import MIMEText
from email.header import Header
def log_content():
if len(sys.argv) == 1:
print("log path is null:1")
exit(1)
path = sys.argv[1]
if path is None:
print("log path is null:2")
exit(1)
if path is None:
print("log path is null:2")
exit(1)
if not os.path.exists(path):
print("log file is not exist")
exit(1)
fp = open(path, "r")
content = fp.read()
fp.close()
return content
# 第三方 SMTP 服务
mail_host = "smtp.@xx.com" # 设置服务器
mail_user = "xxx" # 用户名
mail_pass = "xxx" # 口令
sender = 'xxx@xx.com'
receivers = ['xxx@xx.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
message = MIMEText(log_content(), 'plain', 'utf-8')
message['From'] = Header("congyl@neusoft.com", 'utf-8')
message['To'] = Header("congyl@neusoft.com", 'utf-8')
subject = 'svn备份'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP(host=mail_host, port=587)
smtpObj.starttls()
# smtpObj.set_debuglevel(1)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print("邮件发送成功")
except smtplib.SMTPException as e:
print(e.args)
print("============")
print("Error: 无法发送邮件")
最后,三个脚本都需要在/home/svnbak下,执行:./svnbak.sh即可。
我是用jenkins每天凌晨定时执行脚本,当然你也可以用linux的定时任务执行。