python 多线程备份数据库
import os import time import threading import subprocess # MySQL数据库信息 mysql_host = "192.168.1.199" mysql_port = "3306" mysql_user = "root" mysql_password = "mhsj.net" #数据库密码 mysql_database = "mhsj" #需要备份数据库名 # 备份文件保存路径 backup_path = "/backup" if not os.path.exists(backup_path): os.makedirs(backup_path) # 备份命令 backup_cmd = "mysqldump -h {host} -P {port} -u {user} -p{password} {database} > {filename}" def backup(): # 生成备份文件名 filename = "{database}_{timestamp}.sql".format( database=mysql_database, timestamp=int(time.time()) ) filepath = os.path.join(backup_path, filename) # 执行备份命令 cmd = backup_cmd.format( host=mysql_host, port=mysql_port, user=mysql_user, password=mysql_password, database=mysql_database, filename=filepath ) subprocess.call(cmd, shell=True) print("备份完成:{}".format(filepath)) def main(): # 创建10个线程备份MySQL threads = [] for i in range(10): t = threading.Thread(target=backup) t.start()
由于要备份不同数据库的不同表,所以改造下:
#!/usr/bin/env python # -*- coding: utf-8 -*- # herb import os import time import threading import subprocess # MySQL数据库信息 mysql_host = "192.168.1.199" mysql_port = "3306" mysql_user = "mhsj" mysql_password = "mhsj" # 备份文件保存路径 backup_path = "/home/mysqlbak" if not os.path.exists(backup_path): os.makedirs(backup_path) # 备份命令 backup_cmd = "mysqldump -h {host} -P {port} -u {user} -p{password} {data_talble} > {filename}" def backup_table(database_talble): # 生成备份文件名(因为不同数据库的不同表,所以参数用(数据库 表名)一起传进来) database_name = database_talble.split(" ")[0] table_name = database_talble.split(" ")[1] filename = "{d}_{t}_{timestamp}.sql".format( d=database_name, t=table_name, timestamp=int(time.time()) ) filepath = os.path.join(backup_path, filename) # 执行备份命令 cmd = backup_cmd.format( host=mysql_host, port=mysql_port, user=mysql_user, password=mysql_password, data_talble=database_talble, filename=filepath ) print(cmd) subprocess.call(cmd, shell=True) print("备份完成:{}".format(filepath)) def main(): # 创建4个线程备份MySQL(不同的数据库和对应表一起传参进去) db_table_list = ['mhsj table1', 'mhsj table2', 'herb table3', 'herb001 table4'] threads = [] for d_table in (db_table_list): t = threading.Thread(target=backup_table, args=(d_table,)) #threads.append(t) t.start() main()
转载请注明:梦绘设计 » Python/Shell » python 多线程备份数据库
版权声明
本站《作品展示》类文章均为原创,转载必须注明出处,技术分享类文章部分来源于网络,版权归原作者所有,若侵权请留言。