分享一個(gè)用Python實(shí)現(xiàn)的備份MySQL數(shù)據(jù)庫腳本睡陪,實(shí)現(xiàn)原理是利用Python內(nèi)置的os庫,調(diào)用mysql數(shù)據(jù)庫的mysqldump命令對遠(yuǎn)程數(shù)據(jù)庫或者本地?cái)?shù)據(jù)庫進(jìn)行備份居夹,并計(jì)算出備份的SQL文件大泻烤(單位為kb)诚隙,同時(shí)以備份時(shí)間命名備份的SQL文件既穆,并設(shè)定只保留最近5天的備份記錄赎懦,同時(shí)調(diào)用釘釘群聊機(jī)器人接口,對備份后的數(shù)據(jù)庫信息進(jìn)行消息推送幻工。有需要的運(yùn)維小伙伴可以拿去修改使用励两,這個(gè)腳本在Linux服務(wù)器上使用crontab定時(shí)程序每日定時(shí)運(yùn)行,已經(jīng)運(yùn)行近1年的時(shí)間了囊颅,目前沒有出現(xiàn)任何問題当悔。
import requests
import json
import os
import datetime
if not os.path.exists('mysqldb_backup'):
os.mkdir('mysqldb_backup')
os.chdir('mysqldb_backup')
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=5)
today_file_name = "/home/******/mysqldb_backup/mysql"+str(today)+".sql"
yesterday_file_name = "/home/******/mysqldb_backup/mysql"+str(yesterday)+".sql"
response_code = os.system("/usr/local/mysql/bin/mysqldump -u 數(shù)據(jù)庫用戶名 -p數(shù)據(jù)庫密碼 -h 數(shù)據(jù)庫IP 數(shù)據(jù)庫名稱 > /home/******/mysqldb_backup/mysql`date +%Y-%m-%d`.sql")
file_size = int(os.path.getsize(today_file_name))/1024
if response_code == 0:
text = "#### Message:\n\n > - MySqlDB Backup Completed!\n\n > - SQL_file_size:"+str(round(file_size,4))+"KB"
if os.path.exists(yesterday_file_name):
os.remove(yesterday_file_name)
else:
text = "#### Message:\n\n > - MySqlDB Backup Error!\n\n > - Please check the server program."
dingding_url = "https://oapi.dingtalk.com/robot/send?access_token=釘釘機(jī)器人接口token"
headers = {"Content-Type": "application/json; charset=utf-8"}
post_data = {
"msgtype": "markdown",
"markdown": {
"title":"MySqlDB Backup Message",
"text":text
}
}
requests.post(dingding_url, headers=headers, data=json.dumps(post_data))