Python教程

【PgSQL备份】pg_dump备份pg数据库的python脚本

本文主要是介绍【PgSQL备份】pg_dump备份pg数据库的python脚本,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

pg_dump逻辑备份

对指定数据库进行备份,并对7天前的备份进行清理,将过程信息打印日志

 1 #!/usr/bin/env python
 2 # -*- coding: utf8 -*-
 3 import sys,os,time
 4 from datetime import datetime,timedelta,date
 5 import shutil
 6 
 7 db_user = 'backup'
 8 db_pwd = 'xxxxxx'
 9 db_port = '5431'
10 db_name = 'pgdb'
11 
12 backup_path = '/data/db_dump/'
13 cmd_path = '/usr/local/pgsql/bin/'
14 log_path = backup_path + 'log'
15 
16 # 创建日志函数
17 def writeLogs(filename,contents):
18   f = file(filename,'aw')
19   f.write(contents)
20   f.close()
21 
22 today = backup_path + time.strftime('%Y-%m-%d')
23 fname = today + os.sep + time.strftime('%Y-%m-%d') + '_' + db_name + '.backup'
24 
25 # 创建备份目录
26 if not os.path.exists(today):
27    Msg = '-'*30 + time.strftime('%Y-%m-%d,%H:%M:%S') + '-'*30 + '\n'
28    if(os.mkdir(today)) == None:
29        Msg += '** 成功创建备份目录: ' + today + '\n\n'
30        writeLogs(log_path,Msg)
31    else:
32        Msg += '!! 创建备份目录: ' + today + '失败,请检查目录是否可写!\n\n'
33        writeLogs(log_path,Msg)
34        sys.exit()
35 
36 # 备份pgdb数据库
37 cmd_dump = "%spg_dump -h localhost  -p %s -U %s -F c -b -v -f %s %s" % \
38                (cmd_path,db_port,db_user,fname,db_name)
39 # 执行备份命令
40 if os.system(cmd_dump) == 0:
41    writeLogs(log_path,'数据备份为: ' + fname + '\n')
42 else:
43    writeLogs(log_path,'数据备份失败!\n')
44 ##清理历史备份
45 def is_valid_date(str):
46     '''判断是否是一个有效的日期字符串'''
47     try:
48         time.strptime(str, "%Y-%m-%d")
49         return True
50     except:
51         return False
52 try:
53     define_date = (date.today() + timedelta(days=-7)).strftime("%Y-%m-%d")
54     print("!!!" + define_date + "之前的备份将进行清理!!!")
55     for f in os.listdir(backup_path):
56         if is_valid_date(f):
57             if f < define_date:
58                 rm_f = backup_path + f
59                 print(rm_f)
60                 writeLogs(log_path, '删除过期的日期目录: ' + rm_f + '\n')
61                 shutil.rmtree(rm_f)
62 except OSError as err:
63     print(err)

 

这篇关于【PgSQL备份】pg_dump备份pg数据库的python脚本的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!