python語言實現postgresql數據庫自動備份

#!/usr/bin/env python

# -*- coding: utf8 -*-

import sys,os,time


db_user = 'postgres'

db_pwd = 'postgres'

db_port = '5432'

db_name = 'CCIC2'

backup_path = '/home/sunjc/backupdb/'

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()


# 備份 CCIC2數據庫

cmd_dump = "%spg_dump -i -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')


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章