【Python维护数据库】备份PgSQL实例下指定的数据库
作者:互联网
Postgresql:12.3
Python:2.7.5
利用py脚本备份PgSQL数据库
$ cat db_backup.py #!/usr/bin/env python # -*- coding: utf8 -*- """pg_dump备份PgSQL实例下指定数据库zedb""" import sys,os,time from datetime import datetime,timedelta,date import shutil db_user = 'backup' #db_pwd = 'xxx' db_port = '5432' db_name = 'zedb' backup_path = '/pgshare/db_dump/' cmd_path = '/usr/local/pgsql/bin/' log_path = backup_path + 'log' # 创建日志函数 def writeLogs(filename,contents): f = file(filename,'aw') f.write(contents) f.close() today = backup_path + time.strftime('%Y-%m-%d') fname = today + os.sep + time.strftime('%Y-%m-%d') + '_' + db_name + '.backup' # 创建备份目录 if not os.path.exists(today): Msg = '-'*30 + time.strftime('%Y-%m-%d,%H:%M:%S') + '-'*30 + '\n' if(os.mkdir(today)) == None: Msg += '** 成功创建备份目录: ' + today + '\n\n' writeLogs(log_path,Msg) else: Msg += '!! 创建备份目录: ' + today + '失败,请检查目录是否可写!\n\n' writeLogs(log_path,Msg) sys.exit() # 备份数据库 cmd_dump = "%spg_dump -h localhost -p %s -U %s -F c -b -v -f %s %s" % \ (cmd_path,db_port,db_user,fname,db_name) # 执行备份命令 if os.system(cmd_dump) == 0: writeLogs(log_path,'数据备份为: ' + fname + '\n') else: writeLogs(log_path,'数据备份失败!\n') ##清理历史备份 def is_valid_date(str): '''判断是否是一个有效的日期字符串''' try: time.strptime(str, "%Y-%m-%d") return True except: return False try: define_date = (date.today() + timedelta(days=-7)).strftime("%Y-%m-%d") print("!!!" + define_date + "之前的备份将进行清理!!!") for f in os.listdir(backup_path): if is_valid_date(f): if f < define_date: rm_f = backup_path + f print(rm_f) writeLogs(log_path, '删除过期的日期目录: ' + rm_f + '\n') shutil.rmtree(rm_f) except OSError as err: print(err)
标签:-%,log,Python,数据库,db,PgSQL,path,backup,备份 来源: https://www.cnblogs.com/helon/p/16107729.html