使用python3开发的备份自动化备份脚本,与大家一起分享,一起学习。欢迎大家提出意见,共同进步。
功能介绍:主要实现了本地用xtrabackup备份,备份完成后,把备份文件上传到备份中心。(远程主机)
然后清理本地的备份文件,本地仅保留一个备份文件。上传到远程服务器主要使用了paramiko
```python
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Author:xiaojindou
# Date:2020/05/28
import os
import time
import paramiko
import sys
#config files
back_dir="/home/backup/full"
log_dir="/home/backup/log"
ticks = time.strftime("%Y%d%m_%H%M")
time_log='full_%s.log'%(ticks)
os.system("mkdir -p %s"%back_dir)
os.system("mkdir -p %s"%log_dir)
###用xtrabackup备份数据库
def my_backup(host,user,password,port,my_cnf):
os.system( 'innobackupex --defaults-file=%s --user=%s --password=%s --host %s --port %s %s > %s/%s 2>&1' %(my_cnf, user, password, host, port, back_dir, log_dir, time_log))
#### 定位备份文件
def find_file():
find_find="find {0} -mindepth 1 -maxdepth 1 " "-type d -printf '%P\n' | sort -nr | head -1".format(back_dir)
find_f=os.popen(find_find).read().strip()
bsfile = "%s/%s"%(back_dir,find_f)
return bsfile
###压缩备份文件
def compress():
os.system('tar -zcvPf %s-dbbackup.tar.gz %s --remove-files' %(find_file(),find_file()))
###把备份文件上传到备份中心 76主机
def upload():
##remote host backup center
hostname = '172.29.0.76'
port = 60028
username = 'weihu'
password = '^69Ujxxxxx9p6qWc'
local_path = find_file() + '-dbbackup.tar.gz'
remote_path = '/usr/local/server/mongodb/data/backup_center/' + 'from-lb-tsp-app65-full-' + ticks + '-dbbackup.tar.gz'
if not os.path.isfile(local_path):
print local_path + "file not exist!!!"
sys.exit(1)
try:
s = paramiko.Transport((hostname, port))
s.connect(username = username, password = password)
except Exception as e:
print e
sys.exit(1)
sftp = paramiko.SFTPClient.from_transport(s)
##put file to backup center
sftp.put(local_path, remote_path)
###测试是否上传成功
try: ###如果成功,远程主机会返回一个对象,否则就抛异常。
sftp.file(remote_path)
print "上传成功!"
except IOError:
print "上传失败!"
finally:
s.close()
###删除历史备份集,本地仅保留1份
def remove_backup():
os.system("find %s -name '*-dbbackup.tar.gz' -mtime +1 -exec rm {} \;"%(back_dir))
if __name__ == "__main__":
my_backup('127.0.0.1','root','xxxxxx','13306','/etc/my.cnf')
compress()
upload()
remove_backup()