tidb备份使用的是br进行快照备份 + 日志备份具体代码如下
#qiyewx.pyimport json
from datetime import datetime import requests from config import * # 可以把机器人的配置信息写到一个单独的config里面 也可以直接填到脚本里 class Qiyewx(): def __init__(self): self.corpid = corpid # 企业微信CorpID
self.corpsecret = corpsecret # 应用的Secret
self.agentid = agentid # 应用的AgentID self.touser = touser # 接收提醒的用户账号,多个用户用竖线分隔
self.token = self.get_access_token()
def get_access_token(self): rep = requests.get( f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.corpid}&corpsecret={self.corpsecret}") access_token = json.loads(rep.text).get('access_token') return access_token def send_markdown_msg(self,msg): header = { "Content-Type": "application/json" } data = { "touser": self.touser, "msgtype": "markdown", "agentid": self.agentid, "markdown": { "content": msg } } rep = requests.post(f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={self.token}', headers=header, data=json.dumps(data)) print(rep.text)
# baktidb.py
import psutil import os import subprocess from datetime import datetime from qiyewx import Qiyewx BACKUP_PATH = '/tidb/backup/xxxxx-' + datetime.strftime(datetime.now(), '%Y-%m-%d') def getsize(top): sum_size = 0 for root, dirs, files in os.walk(top, topdown=False): for name in files: size = os.path.getsize(os.path.join(root, name)) sum_size = sum_size + size return f"{sum_size / (1024 ** 3):.2f} GB" bak_command = f"""tiup br backup full --pd "PD地址" --storage "local://{BACKUP_PATH}" --ratelimit 120 --log-file {BACKUP_PATH}.log""" #放到定时任务里面,如果tiup这个命令没有在PATH环境变量里面 需要写绝对路径 try: retcode, output = subprocess.getstatusoutput(bak_command) e = Qiyewx() if retcode != 0: msg = f"**数据库备份**\n>备份时间: {datetime.strftime(datetime.now(), '%Y-%m-%d')} \n>备份目录: {BACKUP_PATH}\n>备份结果: <font color =\"warning\">**失败**</font> \n>消息: {output}" e.send_markdown_msg(msg) elif retcode == 0: a = getsize(BACKUP_PATH) usage = psutil.disk_usage('/') free_disk = f"{usage.free / (1024 ** 3):.2f}GB" msg = f"**数据库备份**\n>备份时间: {datetime.strftime(datetime.now(), '%Y-%m-%d')} \n>备份目录: {BACKUP_PATH}\n>数据大小: {a}\n>备份结果: <font color =\"info\">**正常**</font> \n>剩余磁盘空间: {free_disk}" e.send_markdown_msg(msg) except Exception as e: msg = f"**数据库备份**\n>备份时间: {datetime.strftime(datetime.now(), '%Y-%m-%d')} \n>备份目录: {BACKUP_PATH}\n>备份结果: <font color =\"warning\">**失败**</font> \n>消息: {e}" e.send_markdown_msg(msg)
成功和失败的消息样式
标签:-%,快照,微信,备份,datetime,token,tidb,msg,self From: https://www.cnblogs.com/chentut/p/17648541.html