python自动化脚本之备份mysql数据库

可紊 提交于 2020-05-08 05:48:01

综合别人的python实现备份mysql的自动化脚本,centos7下用python3实现的脚本(python2的只需要修改下print的位置即可)

亲测可执行,且服务器可以定义为其他服务器,未对数据库名是否正确做判断和处理(测试了仅仅输出的备份文件里没什么有效信息而已,不影响)

脚本如下:

 

 1 #!/usr/bin env python3
 2 import os
 3 import time
 4 import datetime
 5 #定义服务器,用户名、密码、数据库名称(多个库分行放置)和备份的路径
 6 DB_HOST = 'localhost'
 7 DB_USER = 'root'
 8 DB_USER_PASSWD = 'mypassword'
 9 DB_NAME = '/mnt/dbbackup/dbnames.txt'
10 BACKUP_PATH = '/mnt/dbbackup/mysql/'
11 
12 DATETIME = time.strftime('%Y%m%d-%H%M%S')
13 TODAYBACKUPPATH = BACKUP_PATH + DATETIME
14 
15 print("createing backup folder!")
16 #创建备份文件夹
17 if not os.path.exists(TODAYBACKUPPATH):
18         os.makedirs(TODAYBACKUPPATH)
19 
20 print("checking for databases names file")
21 
22 
23 #定义执行备份脚本,读取文件中的数据库名称,注意按行读写,不校验是否存在该库
24 def run_backup():
25         in_file = open(DB_NAME,"r")
26         for dbname in in_file.readlines():
27                 dbname = dbname.strip()
28                 print("now starting backup database %s" %dbname)
29                 dumpcmd = "mysqldump -u" +DB_USER + " -p"+DB_USER_PASSWD+" " +dbname+" > "+TODAYBACKUPPATH +"/"+dbname+".sql"
30                 print(dumpcmd)
31                 os.system(dumpcmd)
32         file1.close()
35 #执行压缩的函数
36 def run_tar():
37         compress_file = TODAYBACKUPPATH + ".tar.gz"
38         compress_cmd = "tar -czvf " +compress_file+" "+DATETIME
39         os.chdir(BACKUP_PATH)
40         os.system("pwd")
41         os.system(compress_cmd)
42         print("compress complete!")
43         #删除备份文件夹
44         remove_cmd = "rm -rf "+TODAYBACKUPPATH
45         os.system(remove_cmd)
46 
47 #备份数据库文件存在就执行备份和压缩,否则退出
48 if os.path.exists(DB_NAME):
49         file1 = open(DB_NAME)
50         print("starting backup of all db listed in file "+DB_NAME)
51         run_backup()
52         run_tar()
53         print("backup success!")
54 else:
55         print("database file not found..")
56         exit()

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!