python备份mysql数据库
原本可以用shell完成的功能,现在学习python,就照抄照改。完成数据库备份。
#!/usr/bin/python #-*-coding:utf-8-*- #MYSQL BACK import string,time,os,datetime import sys,logging,stat import 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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。