Python backs up MySQL and synchronizes the rsync server

Source: Internet
Author: User
Tags md5 mysql backup rsync

# vim:tabstop=4 shiftwidth=4 softtabstop=4# Copyright states government as represented by the# Administrator of the National Aeronautics and Space administration.# Copyright, Justin Santa barbara# All rights reserved.# Copyrigh T (c) Citrix Systems, inc.## Licensed under the Apache License, Version 2.0 (the "License"); You may# don't use this file except in compliance with the License. obtain# a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## unless required by a Pplicable law or agreed to in writing, software# distributed under the License are distributed on a "as is" BASIS, with out# warranties or CONDITIONS of any KIND, either express or implied. See the# License for the specific language governing permissions and limitations# under the License.import os,sys,ti    Me,fcntl,structimport commandsimport tracebackimport socketimport shutilimport systry:from hashlib import md5except: From MD5 import Md5defLogging (item,level,mes): LogPath = '/var/log/kxtools/' if not os.path.exists (LogPath): Os.makedirs (LogPath) fp = open ('%s/kxbackup.log '%logpath, ' a ') fp.write ('%s-%s-%s-%s \ n '% (Time.ctime (), item,level,mes)) Fp.close ()        "" "Access File MD5 value" "" Def MD5 (fname): Filemd5 = "" Try:file = Open (fname, "RB") md5f = MD5 ()            STRs = "" While True:strs = File.read (8096) if not strs:break Md5f.update (STRs) filemd5 = Md5f.hexdigest () file.close () return filemd5 except:logging (' MySQL backup ', ' ERROR ', Traceback.format_exc ()) def get_em_ipaddr (dev): s = socket.socket (socket.af_inet, socket. SOCK_DGRAM) IP = Socket.inet_ntoa (Fcntl.ioctl (S.fileno (), 0x8915, # siocgifaddr struct. Pack (' 24s ', dev)) [20:24]) return ipdef ipaddr (): "" "Get host name, IP return (hostname, IP)" "" Def _        GET_IPADDR (): Try:    s = socket.socket (socket.af_inet, socket. SOCK_DGRAM) S.connect (("8.8.8.8", 8000)) return s.getsockname () [0] Except:LOG.err  or (Traceback.format_exc ()) S.close () return (Socket.gethostname (), _get_ipaddr ()) def COMM (cmd): # Call System Commands try:x,y = commands.getstatusoutput (cmd) if x! = 0:log.error (y) print x, Y,cmd return x, y Except:LOG.error (Traceback.format_exc ()) class Backupmysqldb (object): Def __init__ (SE Lf,kwargs): Version = 1.0 Self.kwargs = Kwargs def deletedb (self): # Keep The data backup before T            Wo Days reserve = list () Cctime = Time.time () for F in Os.listdir (self.kwargs[' Backup_path '): If F.find (' GZ ')! = -1:reserve.append (f) for x in reserve:f = '%s%s '% (Self.kwargs [' Backup_path '],x) Fctime = Os.stat (f). St_ctime if (cctime-fctime) > 172800:shutil.move (F, '/data0/reserve/') mes = ' Delete file%s is OK '%f logging (' MySQL backup ', ' INFO ', MES) def backupdb (self): # Dump MySQL db, zip,rsync to server Ctimes = Time.strfti Me ("%y%m%d") Namesql = '%s_%s.sql '% (ctimes,ipaddr () [1]) fname = '%s/%s.gz '% (self.kwargs[' backup_path '],nam ESQL) if not os.path.exists (self.kwargs[' Backup_path '): Os.makedirs (kwargs[' Backup_path ']) # Mys Qldump file to/data0/backup/x, y = COMM ("/usr/local/mysql/bin/mysqldump-u%s-p%s-s/var/lib/mysql/mysql.sock- -opt%s >%s/%s "% (self.kwargs[' user '],self.kwargs[' pass '],self.kwargs[' dbname '],self.kwargs[' Backup_pa Th '],namesql)) if x! = 0:mes = (' mysqldump file%s is failure '%namesql) logging (' MySQL backu P ', ' ERROR ', mes) else:mes = (' mysqldump file%s is OK '%namesql) logging (' MySQL backup ', ' INFO ' , mes) os.chdir (SElf.kwargs[' Backup_path ') # Tar sql file x, y = COMM ("tar-czvf%s.gz%s"% (namesql,namesql)) if x! =            0:mes = (' tar file%s is failure '%namesql) logging (' MySQL backup ', ' ERROR ', mes) Else:  Mes = (' tar file%s is OK '%namesql) logging (' MySQL backup ', ' INFO ', mes) # Create MD5 values MD5        = MD5 (fname) newname = Fname.split ('. sql.gz ') [0] + ' _%s '%md5 + '. sql.gz ' Shutil.move (fname, NewName) # Rsync to server 192.168.223.51 x, y = COMM ("Rsync-avz%s%s::%s/"% (newname,self.kwargs[' rsync_ip '],self.kw args[' Rsync_model ')) if x! = 0:mes = "Rsync file%s.gz is failure"%namesql logging (' MySQL Backup ', ' ERROR ', mes) else:mes = "Rsync file%s.gz is ok"%namesql logging (' MySQL backup ', ' in        FO ', mes) # Delete SQL file Shutil.move (namesql, '/dev/null ') def work (self): Self.deletedb () Self.backupdb () if __name__ = = "__main__": Kwargs = {' user ': ' admin ', ' Pass ': ' admin ', ' host ': ' localhost ', ' db ' Name ': ' Abbs ', ' rsync_ip ': ' 192.168.223.51 ', ' rsync_model ': ' Abbs_backup ', ' backup_path ': '/data0 /backup/'} sc = backupmysqldb (Kwargs) sc.work ()


This article comes from the blog, "since it's here, leave something behind", make sure to keep this source http://swq499809608.blog.51cto.com/797714/1407211

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.