Linux下Python备份mysql脚本代码
【摘要】 前言需要在linux下备份mysql数据代码#!/usr/bin/python# vim: set fileencoding=utf-8import osimport timeDB_HOST = 'localhost'DB_USER = '用户名'DB_USER_PASSWORD = '密码'#DB_NAME = '/backup/dbnames.txt'DB_NAME = 'zhongsh...
前言
需要在linux下备份mysql数据
代码
#!/usr/bin/python
# vim: set fileencoding=utf-8
import os
import time
DB_HOST = 'localhost'
DB_USER = '用户名'
DB_USER_PASSWORD = '密码'
#DB_NAME = '/backup/dbnames.txt'
DB_NAME = '数据库名称'
BACKUP_PATH = '/backup/dbbackup/'
DATETIME = time.strftime('%m%d%Y-%H%M%S')
TODAYBACKUPPATH = BACKUP_PATH + DATETIME
print("创建备份文件夹")
print(TODAYBACKUPPATH)
if not os.path.exists(TODAYBACKUPPATH):
os.makedirs(TODAYBACKUPPATH)
print("检查数据库名称文件.")
if os.path.exists(DB_NAME):
file1 = open(DB_NAME)
multi = 1
print("数据库文件发现...")
print("开始备份文件中列出的所有dbs " + DB_NAME)
else:
print("未找到数据库文件...")
print("启动数据库备份 " + DB_NAME)
multi = 0
#启动实际的数据库备份进程。
if multi:
in_file = open(DB_NAME,"r")
flength = len(in_file.readlines())
in_file.close()
p = 1
dbfile = open(DB_NAME,"r")
while p <= flength:
db = dbfile.readline() # reading database name from file
db = db[:-1] # deletes extra line
dumpcmd = "mysqldump -u " + DB_USER + " -p" + DB_USER_PASSWORD + " " + db + " > " + TODAYBACKUPPATH + "/" + db + ".sql"
os.system(dumpcmd)
p = p + 1
dbfile.close()
else:
db = DB_NAME
dumpcmd = "mysqldump -u " + DB_USER + " -p" + DB_USER_PASSWORD + " " + db + " > " + TODAYBACKUPPATH + "/" + db + ".sql"
os.system(dumpcmd)
print("备份脚本完成")
print("您的备份已在 '" + TODAYBACKUPPATH + "' 目录")
结论
#!/usr/bin/python
# vim: set fileencoding=utf-8
linux上需要的代码,如果需要在windows下执行去掉即可
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)