1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| import os import subprocess import time
import oss2
import requests
def execute(command): """ 执行命令
:param command: str 命令字符串 :return: str 命令执行后的返回值,标准输出和标准错误 """ result = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE, encoding='utf8') out, err = result.communicate() return result.returncode, out, err
def rm_file(file_name): """ 删除文件
:param file_name: 需要删除的文件路径 :return: None """ execute(f'rm {file_name}')
def back_mysql(): """ 执行备份逻辑
:return: 错误信息标题和错误信息具体内容 """ file_name = f'back-{time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime())}.sql' return_code, out, err = execute(command=f'mysqldump --login-path=local --all-databases > "{file_name}"') if not return_code: if os.path.exists(file_name): return_code, out, err = execute(f'7z a -p123456 "{file_name}.7z" "{file_name}"') if not return_code: print(f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())} 备份成功') rm_file(file_name=file_name) return upload_file(f'{file_name}.7z') else: return '压缩失败', f'压缩失败,错误信息为:\n\nerr:{err}\n\nout:{out}' else: return '备份成功', '备份成功,但文件不存在' else: return '数据库备份出错', f'mysqldump 备份出错,错误信息为\n\nerr: {err}\n\nout:{out}'
def upload_file(file_name): """ 上传文件
:param file_name: 需要上传的文件名 :return: 错误信息标题和错误信息内容 """ auth = oss2.Auth('LxxxxxxG', 'SxxxxxxY') bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'xxxxxx') result = bucket.put_object_from_file(f'xxxxx/{file_name}', file_name) if result.status == 200: print(f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())} 上传成功!') rm_file(file_name) return else: print(f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())} 上传失败!') return '上传失败!', f'错误状态码为:{result.status}'
def send_message(text, desp): """ 发送到微信通知
:param text: 消息标题 :param desp: 消息内容 :return: None """ url = 'https://sc.ftqq.com/SCUxxxxxxa.send' data = { 'text': text, 'desp': desp } requests.post(url=url, data=data) print(data)
if __name__ == '__main__': message = back_mysql() if message: send_message(*message)
|