目的:为了解决修改关键或者基础数据导致项目出现问题,所以,备份是很有必要的,并且解决备份文件过多的问题。
前提:备份的本机必须安装Mysql,否则Mysql命令报错。
使用:linux一般自带python,执行脚本:python sql_bak.py 即可。
(PS: 如果不小心python后面没输入内容,可输入exit()即可推荐python命令行)
# -*- coding: utf-8 -*- # Import required python libraries # pancx 2019-04-10 import os import time import datetime import shutil # MySQL database details to which backup to be done. Make sure below user having enough privileges to take databases backup. #数据库ip DB_HOST = "" #数据库端口 DB_PORT = "10111" #这里填数据库用户名 DB_USER = "root" #数据库密码 DB_USER_PASSWORD = "\'(ink^zm+36ygZvgXPjq#*k_Xd=&18!\'" #需要备份的数据库 DB_NAMES = "order,act,ggg" #需要备份到的路径 BACKUP_PATH = "/sqlbak/" # Getting current datetime to create seprate backup folder like "20190412". DATETIME = time.strftime('%Y%m%d') TODAYBACKUPPATH = BACKUP_PATH + DATETIME # Checking if backup folder already exists or not. If not exists will create it. if not os.path.exists(TODAYBACKUPPATH): os.makedirs(TODAYBACKUPPATH) today = datetime.datetime.now() for item in os.listdir(BACKUP_PATH): try: foldername = os.path.split(item)[1] day = datetime.datetime.strptime(foldername, "%Y%m%d") diff = today - day if diff.days >= 90: print('- - - del folder three months ago: ' + BACKUP_PATH + item) shutil.rmtree(BACKUP_PATH + item) except: pass # Code for checking if you want to take single database backup or assinged multiple backups in DB_NAME. DBS = DB_NAMES.split(",") for DB_NAME in DBS: # Starting actual database backup process. DB_PATH = TODAYBACKUPPATH + "/" + DB_NAME + ".sql.gz" print("- - - baking '" + DB_NAME + ".sql'") dumpcmd = "mysqldump -h" + DB_HOST + " -P" + DB_PORT + " -u" + DB_USER + " -p" + DB_USER_PASSWORD + " --databases " + DB_NAME + " --set-gtid-purged=OFF |gzip > " + DB_PATH os.system(dumpcmd) print("- - - Your backups has been created in '" + TODAYBACKUPPATH + "' directory") # mysqldump: [Warning] Using a password on the command line interface can be insecure. 在命令行输入密码,就会提示这些安全警告信息(警告信息可忽略)