通過python定時下載阿里云RDS二進制日志

需求:數(shù)據(jù)庫使用的阿里云RDS,上面設置的日志保存為一個月,需要保存一個月之后的二進制日志。

方法:通過python腳本對接阿里云api接口,結(jié)合crontab定時任務可實現(xiàn)定時下載即將被清除的日志。

腳本如下:


#!/usr/bin/env python3

# -*- coding: utf-8 -*-

# @Time    : 2018-12-12 13:52

# @Author  : opsonly

# @Site    :

# @File    : rds_binlog.py

# @Software: PyCharm

'''

下載阿里云rds binlog日志

'''

import base64,urllib.request

import hashlib

import hmac

import os

import uuid,time,json,wget

import time,datetime

class RDS_BINLOG_RELATE(object):

    def __init__(self):

        self.access_id = 'xxxxxxxxx' #阿里云access_id

        self.access_key = 'xxxxxxxxx' #阿里云access_key

    #通過id和key來進行簽名

    def signed(self):

        today = datetime.date.today()

        first = today.replace()

        lastMonth = first - datetime.timedelta(days=30)

        lastMonth2 = first - datetime.timedelta(days=29)

        starttime = lastMonth.strftime("%Y-%m-%dT%H:%M:%SZ")

        endtime = lastMonth2.strftime("%Y-%m-%dT%H:%M:%SZ")

        timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())

        header = {

            'Action': 'DescribeBinlogFiles',

            'DBInstanceId': 'rm-xxxxxxxxxx', #RDS實例id

            'StartTime': starttime,

            'EndTime': endtime,

            'Format': 'JSON',

            'Version': '2014-08-15',

            'AccessKeyId': self.access_id,

            'SignatureVersion': '1.0',

            'SignatureMethod': 'HMAC-SHA1',

            'SignatureNonce': str(uuid.uuid1()),

            'TimeStamp': timestamp,

        }

        #對請求頭進行排序

        sortedD = sorted(header.items(), key=lambda x: x[0])

        url = 'https://rds.aliyuncs.com'

        canstring = ''

        #將請求參數(shù)以#連接

        for k, v in sortedD:

            canstring += '&' + self.percentEncode(k) + '=' + self.percentEncode(v)

        #對請求連接進行阿里云要的編碼規(guī)則進行編碼

        stiingToSign = 'GET&%2F&' + self.percentEncode(canstring[1:])

        bs = self.access_key + '&'

        bs = bytes(bs, encoding='utf8')

        stiingToSign = bytes(stiingToSign, encoding='utf8')

        h = hmac.new(bs, stiingToSign, hashlib.sha1)

        stiingToSign = base64.b64encode(h.digest()).strip()

        #將簽名加入到請求頭

        header['Signature'] = stiingToSign

        #返回url

        url = url + "/?" + urllib.parse.urlencode(header)

        return url

    #按照規(guī)則替換

    def percentEncode(self,store):

        encodeStr = store

        res = urllib.request.quote(encodeStr)

        res = res.replace('+', '%20')

        res = res.replace('*', '%2A')

        res = res.replace('%7E', '~')

        return str(res)

    #篩選出鏈接下載二進制日志文件

    def getBinLog(self):

        binlog_url = self.signed()

        req = urllib.request.urlopen(binlog_url)

        req = req.read().decode('utf8')

        res = json.loads(req)

        logDir = '/data/backup/mysqlbinlog/'

        ntoday = datetime.date.today()

        nfirst = ntoday.replace()

        nlastMonth = nfirst - datetime.timedelta(days=30)

        bakmonth = nlastMonth.strftime("%Y%m%d")

        backdir = logDir + bakmonth

        os.mkdir(backdir)

        os.chdir(backdir)

        for i in res['Items']['BinLogFile']:

            wget.download(i['IntranetDownloadLink'])

s = RDS_BINLOG_RELATE()

s.getBinLog()

腳本地址:https://github.com/opsonly,上面還有許多阿里云api腳本和常用shell腳本,歡迎star。

喜歡我寫的東西的朋友可以關(guān)注一下我的公眾號,上面有我的學習資源以及一些其他福利。:Devops部落

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • 今天早上我的學員終于生了,女孩,特別結(jié)實,特別可愛。 第一胎,十二點多去醫(yī)院,兩點開兩指,四點開四指,五點半十指全...
    渦孩緹閱讀 290評論 0 1
  • 女人買衣服,永遠都不夠。衣柜里,總少了那件最想穿的。但是,怎么給寶寶買衣服,也變成這樣了呢?我翻著寶寶的衣柜,這越...
    珍妮LEE閱讀 811評論 0 0
  • 042.昨天開聯(lián)席會,雖然感慨這次考的差,但是老師們也都肯定了班級紀律好很多了,尤其物理老師說,上課心情好多了,看...
    黎明初曉閱讀 165評論 0 0
  • 2018 年11 月14日 陰 在透過陽光的縫隙中,我在休息室爬樓聽寫作訓練營的第三課,談自己寫作的初心,內(nèi)心有點...
    尋夢如初閱讀 477評論 0 5
  • 其實迷茫就是人生的一種常態(tài),不管你是什么身份,也不管你從事什么工作。 不論是你少年,青年,中年,或者是老年,人生中...
    安樂無憂閱讀 402評論 0 5

友情鏈接更多精彩內(nèi)容