使用Python从rds上下载mysql

发布时间:2019-08-29 07:36:04编辑:auto阅读(1514)

    #!/usr/bin/python2.6
    #coding=utf-8
    from aliyunsdkcore import client
    from aliyunsdkrds.request.v20140815 import DescribeBackupsRequest
    from aliyunsdkrds.request.v20140815 import DescribeBinlogFilesRequest
    import json
    import urllib
    import datetime
    import subprocess
    import warnings
    from retrying import retry
    
    warnings.filterwarnings("ignore")
    
    datadir="/backup01/databackup"
    binlogdir="/backup02/binlogbackup"
    
    # 获得时间需要备份的时间范围
    def getdate():
            global start_date
            global end_date
            ti = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M')
            time1 = datetime.datetime.strptime(ti,'%Y-%m-%d %H:%M')
            time11 = time1 - datetime.timedelta(hours=8)
            end_date = datetime.datetime.strftime(time11,'%Y-%m-%dT%H:%MZ')
            time22 = time11 - datetime.timedelta(days=1)# 现在前一天的备份
            start_date = datetime.datetime.strftime(time22,'%Y-%m-%dT%H:%MZ')
            return 0
            
            
    #回调函数
    def Schedule(a,b,c):
            '''
                    a:已经下载的数据块
                    b:数据块的大小
                    c:远程文件的大小
            '''
            per = 100.0 * a * b / c
            if per > 100:
                    per = 100
                    print '%.2f%%' % per
                    
                    
    # 拉取指定db_instanceid的备份文件
    @retry(wait_fixed=10000,stop_max_attempt_number=10)
    def downfullbackupfile(db_instanceid):
            print db_instanceid
            startdate = start_date
            enddate = end_date
            clt = client.AcsClient('11111','2222','cn-hangzhou')
            request = DescribeBackupsRequest.DescribeBackupsRequest()
            request.set_accept_format('json')
            request.set_action_name('DescribeBackups')
            request.set_DBInstanceId(db_instanceid)
            request.set_StartTime(startdate)
            request.set_EndTime(enddate)
            result = clt.do_action(request)
            s=json.loads(result)
            list = s['Items']['Backup']
            for i in list:
                    DBInstanceId = i['DBInstanceId']
                    url = i['BackupDownloadURL']
                    idx = url.index('tar.gz')
                    filename = url[7:idx+6].replace('/','_')
                    Fname="%s_%s" % ( DBInstanceId,filename)
                    filename = "%s/%s_%s" % (datadir,DBInstanceId,filename)
                    downfile(url,filename)
            return 1
            
            
    @retry(wait_fixed=10000,stop_max_attempt_number=10)
    def downfile(url,filename):
            urllib.urlretrieve(url,filename,Schedule)
            print filename
            return 1
            
            
    # 拉取指定db_instanceid的备份文件
    @retry(wait_fixed=10000,stop_max_attempt_number=10)
    def downbinlogfile(db_instanceid):
            startdate = start_date.replace("Z",":00Z")
            enddate = end_date.replace("Z",":00Z")
            clt = client.AcsClient('1111','2222','cn-hangzhou')
            request = DescribeBinlogFilesRequest.DescribeBinlogFilesRequest()
            request.set_accept_format('json')
            request.set_action_name('DescribeBinlogFiles')
            request.set_DBInstanceId(db_instanceid)
            request.set_StartTime(startdate)
            request.set_EndTime(enddate)
            result = clt.do_action(request)
            s=json.loads(result)
            list = s['Items']['BinLogFile']
            for i in list:
                    DBInstanceId = db_instanceid
                    url = i['DownloadLink']
                    idx = url.index('.tar?OSSAccessKeyId')
                    filename = url[7:idx+4].replace('/','_')
                    Fname="%s_%s" % (DBInstanceId,filename)
                    filename = "%s/%s_%s" % (binlogdir,DBInstanceId,filename)
                    downfile(url,filename)
            return 1  
            
                  
    #需要备份的db_instanceid
    def dblist():
    # rdsvm2l47islz43z5f09
            dblist = ['1111','2222','3333']
            for db in dblist:
                    downfullbackupfile(db)
                    downbinlogfile(db)
                    
                    
    # 清理重复的binlog备份
    def clearbinlog():
            cmd="find /backup/binlogbackup -name  '*hostins977917*' |  xargs rm  -rf ; find /backup/binlogbackup -name  '*hostins1465579*' |  xargs rm  -rf"
            subprocess.call(cmd,shell=True) 
    try:
            if __name__ == "__main__":
                    getdate()
                    dblist()
    #               clearbinlog()
    except Exception,e:
            print e

关键字