python備份mysql資料庫

來源:互聯網
上載者:User

標籤:mysql   python   Database Backup   

原本可以用shell完成的功能,現在學習python,就照抄照改。完成Database Backup。

 

#!/usr/bin/python#-*-coding:utf-8-*-#MYSQL BACKimport string,time,os,datetimeimport sys,logging,statimport subprocess#os.environ.get(‘PERONA_A’)os.environ["PATH"]="/usr/local/mysql/bin/:"# os.putenv("PATH","/usr/local/mysql/bin/:")#os.putenv(“PATH”,”/usr/bin/”)# os.environ["PATH"]year= time.strftime(‘%Y‘,time.localtime(time.time()))moth= time.strftime(‘%m‘,time.localtime(time.time()))data_path ="/mysqlbak/"+year+"/"+moth+"/"sql_user ="root"sql_pwd ="sh123456"sql_ip ="127.0.0.1"all="--all-databases --events"def loger(datapath,logfile="mysqlbak.log"):    """建立記錄檔"""    if not os.path.exists(datapath):        os.makedirs(datapath)    log_filename = datapath+logfile    log_format = ‘%(filename)s [%(asctime)s] [%(levelname)s] %(message)s‘         logging.basicConfig(filename=log_filename,format=log_format,datefmt=‘%Y-%m-%d %H:%M:%S %p‘,level=logging.DEBUG)#----------------------------------------------------------------------def ClearDir(dir,age):    """刪除幾天前的檔案,age為時間長,如(86400為一天)"""    for file in os.listdir(dir):        now = time.time()        filepath = os.path.join(dir,file)        files = os.stat(filepath).st_mtime        if files < now - age:            if os.path.isfile(filepath):                os.remove(filepath)                logging.info("%s remove success!!!" % filepath)   def mysql_backup(filename):    backup_name = data_path+filename+"%s.sql" %(time.strftime("%Y%m%d%H%M"))      sql_comm =‘mysqldump %s -h%s -u%s -p%s > %s‘%(all,sql_ip,sql_user,sql_pwd,backup_name)    #print sql_comm    if os.system(sql_comm) ==0:        return logging.info("%s back success!!!!" %backup_name)        #print "scuess !"    else:        return logging.error("%s back Failed!!!" %backup_name)        #print "Failer !!!!"#----------------------------------------------------------------------   if __name__ =="__main__":    loger(data_path)    SQL_backup =mysql_backup("app_")    ClearDir(data_path,(7 * 86400))

 

本文出自 “紅蘋果” 部落格,請務必保留此出處http://262242.blog.51cto.com/252242/1571994

python備份mysql資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.