Originally can be done with the Shell function, now learn python, copy the changes. Complete the 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"): "" " Create the log file "" " if not os.path.exists (datapath): os.makedirs (DataPath) log_filename = datapath+logfile log_format = '% (filename) s [% (asctime) s] [% (levelname) s] % (message) S ' &NBSP;&NBSP;&NBSP;&NBSp; logging.basicconfig (filename=log_filename,format=log_format,datefmt= '%Y-%m-%d %h:%m:%s %p ', level=logging. DEBUG) #----------------------------------------------------------------------Def cleardir (dir,age): "" "Delete files from a few days ago, age is long, e.g. (86400 for one day)" "" 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))
This article is from the "Red apple" blog, please be sure to keep this source http://262242.blog.51cto.com/252242/1571994
Python backup MySQL Database