#废话不多说,直接上代码。您有好的意见,可以留言!共同探讨,一起进步!

宗旨:

一起努力,一起进步!


# !/usr/bin/python# coding=utf-8

import jsonimport osimport datetimeimport urllibfrom aliyunsdkcore import clientfrom aliyunsdkrds.request.v20140815.DescribeBackupsRequest import DescribeBackupsRequestfrom aliyunsdkrds.request.v20140815.DescribeBinlogFilesRequest import DescribeBinlogFilesRequest

class PullBackupfile():    def __init__(self,accessid,key,region,instanceid):        self.accessid = accessid        self.key = key        self.region = region        self.instanceid = instanceid    #自动创建备份目录    def mkdir(self):        now = datetime.date.today() - datetime.timedelta(days=1)        path = 'D:\databack\%s' % now        data_path = os.path.join(path, 'data')        bin_log_path = os.path.join(path, 'binlog')        path_list = [path, data_path, bin_log_path]        for i in path_list:            if os.path.isdir(i):                continue            else:                os.popen('mkdir %s' % i)        return data_path,bin_log_path

    def login(self):        clt = client.AcsClient(self.accessid,self.key,self.region)        return clt

    # 阿里云返回的数据为UTC时间,因此要转换为东八区时间。2013-08-15T12:00:00Z为北京时间2013年8月15日20点0分0秒。    def backup_time(self,name):        now = datetime.datetime.now()        #零点        end_time = now - datetime.timedelta(hours=now.hour + 8, minutes=now.minute, seconds=now.second,                                            microseconds=now.microsecond)        start_time = end_time - datetime.timedelta(days=1)        #时间格式不相同        if name == 'datafile':            starttime = start_time.strftime('%Y-%m-%dT%H:%MZ')            endtime = end_time.strftime('%Y-%m-%dT%H:%MZ')        if name == 'binlog':            starttime = start_time.strftime('%Y-%m-%dT%H:%M:%SZ')            endtime = end_time.strftime('%Y-%m-%dT%H:%M:%SZ')        return starttime,endtime
def download_rds_backfile(self):    data_path,bin_log_path = self.mkdir()    starttime,endtime = self.backup_time('datafile')    try:        req_bakup = DescribeBackupsRequest()        req_bakup.set_DBInstanceId(self.instanceid)        req_bakup.set_accept_format('json')        req_bakup.set_StartTime(starttime)        req_bakup.set_EndTime(endtime)        clt  = self.login()        backup = clt.do_action_with_exception(req_bakup)        jsload = json.loads(backup)        num = jsload["PageRecordCount"]        print("backfiles:" + str(num))        i = 0        back_path = os.path.join(data_path,'')        while i < num:

            bak_url = jsload["Items"]["Backup"][i]["BackupDownloadURL"]            bak_host = jsload["Items"]["Backup"][i]["HostInstanceID"]            bak_id = jsload["Items"]["Backup"][i]["BackupId"]            print ("BackupId:" + str(bak_id), "HostInstanceID:" + str(bak_host), "downloadurl:" + bak_url)            save_name = back_path + bak_url.split('?')[0].split('/')[-1]            u = urllib.request.urlopen(bak_url)            f_header = u.info()            print(f_header)            bak_size = int(f_header["Content-Length"])

            print ("backup file size: %s M ,fime nema: %s" % (bak_size / 1024 / 1024, save_name))

            with open(save_name, "wb") as f:

                file_size_dl = 0                block_sz = 8192                while True:                    buffer = u.read(block_sz)                    if not buffer:                        break

                    file_size_dl += len(buffer)                    f.write(buffer)                    status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / bak_size)                    # status = status + chr(8) * (len(status) + 1)                    print (status)            i = i + 1            print ("download complet!")    except:        print("无备份")

    # 备份binlog 下载到本地服务器    def download_rds_binlog(self):        data_path, bin_log_path = self.mkdir()        print(bin_log_path)        starttime,endtime = self.backup_time('binlog')        try:            request = DescribeBinlogFilesRequest()            request.set_DBInstanceId(self.instanceid)            request.set_accept_format('json')            request.set_StartTime(starttime)            request.set_EndTime(endtime)            clt = self.login()            binlog_backup = clt.do_action_with_exception(request)            jsload = json.loads(binlog_backup)            num = jsload["TotalRecordCount"]            print("backfiles:" + str(num))            i = 0            back_path = os.path.join(bin_log_path,'')            print(back_path)            while i < num:                bak_url = jsload["Items"]["BinLogFile"][i]["DownloadLink"]                bak_host = jsload["Items"]["BinLogFile"][i]["HostInstanceID"]                bak_name = jsload["Items"]["BinLogFile"][i]["LogFileName"]                bak_size = jsload["Items"]["BinLogFile"][i]["FileSize"]                bak_time = datetime.datetime.strptime(jsload["Items"]["BinLogFile"][i]['LogEndTime'],'%Y-%m-%dT%H:%M:%SZ')                # print("LogFileName:" + str(bak_name), "HostInstanceID:" + str(bak_host), "downloadurl:" + bak_url)                save_name = back_path + bak_name + '_' + str(bak_time).replace(' ','').replace(':','').replace('-','')                # print("backup file size: %s M ,fime nema: %s" % (bak_size / 1024 / 1024, save_name))                with open(save_name, "wb") as f:                    urllib.request.urlretrieve(bak_url,save_name)                i = i + 1                print("download complet!")        except:            print('无备份')    #删除超过7天的文件夹及子目录,windows 命令    def remove_file(self):        os.popen('forfiles /p "D:\databack" /d -7 /c "cmd /c echo deleting @path  ... && rd @path /s /q" ')

if __name__ == '__main__':    pull_file = PullBackupfile('accessid','key','region','instanceid')
    pull_file.download_rds_backfile()    pull_file.download_rds_binlog()    pull_file.remove_file()

转载于:https://www.cnblogs.com/leeInvisible/p/11582608.html

python 下载阿里云mysql的备份文件及binlog到本地相关推荐

  1. 通过python下载阿里云RDS备份数据库

    创建python脚本 #!/usr/bin/env python #coding=utf-8from aliyunsdkcore.client import AcsClient from aliyun ...

  2. 阿里云mysql数据备份恢复数据到本地mysql(备份+binlog)

    参考:https://help.aliyun.com/knowledge_detail/41817.html?spm=a2c4g.11186623.4.3.49bf4292RNNrSC 起因:生产环境 ...

  3. python自动下载阿里云数据库数据_脚本自动下载阿里云每日备份数据库镜像

    脚本自动下载阿里云每日备份数据库镜像 背景 前端时间街道一个临时需求,要求根据每日的数据快照,统计计算出需要数据结果,并写入数据库,提供查询接口. 遇到两个自己没有尝试过的点: 阿里云导出的数据库是. ...

  4. Python实现阿里云aliyun服务器里的文件上传与下载

    Python实现阿里云服务器里的文件上传与下载 Python实现阿里云服务器里的文件上传与下载 背景: 正文: 预备环境: 构想: 实现: 注意: 结尾 018.4.15 背景: 老实说,因为现实的各 ...

  5. 阿里云mysql容量_阿里云RDS的mysql数据库占用空间超过90%的处理

    阿里云RDS数据库最大支持2T,目前已经占用了90%,如果进行分库或者迁移比较麻烦,思路是找出占用空间过大的日志或不重要的文件进行删除操作 查询所有数据库占用磁盘空间大小的SQL语句: show bi ...

  6. python连接阿里云odps

    怎么下载他的库这个就自行百度了,配置完毕之后就用以下代码即可用python连接阿里云odps的数据库了. from odps import ODPS o = ODPS('嘿嘿嘿', #这个地方是阿里云 ...

  7. c 访问阿里云mysql_本地怎样访问阿里云mysql数据库服务器

    全网最新活动请看下方内容或右侧内容! --------------- 本地怎样访问阿里云mysql数据库服务器,在阿里云上放数据库. 对于大多数小型或初期项目来说,我们可能常用的做法是先将web.数据 ...

  8. python学习之路:python连接阿里云ODPS

    python学习之路:python连接阿里云ODPS 前言 本人最近在学习使用ODPS,希望把学习过程记录下来,方便自己查阅. 1.安装ODPS pip install ODPS 2.连接阿里云odp ...

  9. Linux环境Shell脚本上传下载阿里云OSS文件

    为什么80%的码农都做不了架构师?>>>    Linux环境Shell脚本上传下载阿里云OSS文件 背景 工作中由于我们项目生成的日志文件比较重要,而本地磁盘空间有限存储不了多久, ...

最新文章

  1. java mongodb save,Java MongoDB一次保存多个文档
  2. python大一考试_python 考试补缺
  3. centos6.0编译安装mysql5.5脚本
  4. Android 驱动开发(14)---深入学习Linux Device Tree
  5. 腾讯云推出首款自研服务器星星海;苹果新款Mac Pro整套配齐超30万;Fedora 31稳定版发布|极客头条...
  6. 【luogu】P1772物流运输(最短路+DP)
  7. LayaAir Graphics.drawTexture 显示与切换图片
  8. android 色彩搭配,设计学堂:关于APP配色的一些常用色彩搭配技巧
  9. hodj 1008 Elevator (模拟题)
  10. 逻辑谬误_大规模分布式计算的谬误
  11. java做度量衡换算器_简易单位换算器_度量衡单位转换
  12. 绘制自己的人际关系图_总算懂了如何画人际关系图
  13. C#调用Outlook发送邮件
  14. 钱包开发经验分享:BTC篇
  15. ISO/IEC 9126 软件质量模型
  16. 信息安全-期末复习题
  17. Attribute特性定义及应用
  18. openwrt使用port-mirroring
  19. 前端笔试面试题之三(2015美的前端笔试)
  20. Java程序员面试笔记pdf,JqGrid完整例子

热门文章

  1. PHP+mysql+ajax搭建图书管理系统
  2. JQuery图片无限循环滚动源码
  3. [leetcode笔记] Remove Duplicates from Sorted List II
  4. error_reporting笔记
  5. 大端(Big Endian)与小端(Little Endian)详解
  6. getopt:命令行选项、参数处理
  7. 图形算法 - 模糊函数比较,Blur Function Compare
  8. 池化方法总结(Pooling)
  9. Python学习之路:NumPy初识
  10. timestamp with local time zone类型和timestamp with time zone