利用python定時備份數據庫並上傳到ftp,代碼: python
import os; import time; import tarfile; import shutil; import ftplib; import datetime dumpdir = 'D:/oraclebak/';#oracle dmp的存儲路徑 tardir = 'D:/dumptar/' dbList = ('user1','user2','user3');#oralce用戶 ftpdir = '/ftp/dump/';#ftp存儲路徑 ##循環執行oracle備份命令 for dbname in dbList: command = "expdp userid='sys/syshaha@localhost/orcl as sysdba' \ directory=DUMP_DIR dumpfile=%s.dmp,logfile=%s.log schemas=%s" %(dbname,dbname,dbname); os.system(command); tar_file = time.strftime('%Y-%m-%d_%H-%M-%S')+'.tar.gz';#建立tar文件 tar = tarfile.open(tardir+tar_file,'w:gz'); ##循環將dmp文件壓縮到tar文件,而後刪除dmp文件 for root,dir,files in os.walk(dumpdir): for file in files: fullpath = os.path.join(root,file); tar.add(fullpath,arcname=file); if os.path.isfile(fullpath): os.remove(fullpath); elif os.path.isdir(fullpath): shutil.rmtree(fullpath,True); tar.close(); ## 上傳到ftp ftp = ftplib.FTP(); ftp.connect('192.168.10.6','21'); ftp.login('dump','dumphaha'); #根據月份建立目錄 monthdir = time.strftime('%Y%m'); try: ftp.cwd(ftpdir+monthdir); except ftplib.error_perm: ftp.mkd(ftpdir+monthdir); ftp.cwd(ftpdir+monthdir); f = open(tardir+tar_file,'rb'); #print tar_file ftp.storbinary('STOR '+tar_file,f); f.close(); ##刪除上一月份的備份文件,以減小ftp存儲空間 lastmonthdir = ''; lastmonth = datetime.date.today().month-1 if lastmonth<10: lastmonthdir = str(datetime.date.today().year)+'0'+str(lastmonth); elif lastmonth == 0: lastmonthdir = str(datetime.date.today().year-1)+ '12'; else: lastmonthdir = str(datetime.date.today().year)+ str(lastmonth); #print lastmonthdir; try: ftp.cwd(ftpdir+ lastmonthdir); for lastfile in ftp.nlst(): try: #print lashfile ftp.delete(lastfile); except Exception,e: ftp.rmd(ftpdir+lastmonthdir); print e; #ftp.rmd(lastfile); ftp.rmd(ftpdir+ lastmonthdir); except ftplib.error_perm,e: print e; ftp.quit(); os.remove(tardir+tar_file);
window下定製執行python數據庫
將以上代碼保存爲.py文件,而後設置window任務計劃程序oracle
設置執行程序ui