Python自动备份脚本

Posted pcxx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python自动备份脚本相关的知识,希望对你有一定的参考价值。

目的:为了解决修改关键或者基础数据导致项目出现问题,所以,备份是很有必要的,并且解决备份文件过多的问题。

前提:备份的本机必须安装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 = "www.tencentcdb.com"
#数据库端口
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. 在命令行输入密码,就会提示这些安全警告信息(警告信息可忽略)

 

以上是关于Python自动备份脚本的主要内容,如果未能解决你的问题,请参考以下文章

python编写Mysql自动备份脚本

mysql 自动备份脚本

常用python日期日志获取内容循环的代码片段

python多线程自动备份华为H3C交换机配置和LOG

Linux(CentOS7)设置自动备份数据库到阿里云OSS

web服务文件更新自动同步数据库主从复制shell脚本实现网站代码备份和mysql备份