当前位置:   article > 正文

Python 基于docker部署的Mysql备份查询脚本

Python 基于docker部署的Mysql备份查询脚本

前言

此环境是基于docker部署的mysql,docker部署mysql可以参考如下链接:

docker 部署服务案例-CSDN博客

颜色块文件

  1. root@bogon:~ 2024-04-18 16:34:23# cat DefaultColor.py
  2. #########################################################################
  3. # File Name: DefaultColor.py
  4. # Author: eight
  5. # Mail: 18847097110@163.com
  6. # Created Time: Thu 11 Apr 2024 10:25:31 PM CST
  7. #########################################################################
  8. #!/usr/bin/env python
  9. # -*- coding: utf-8 -*-
  10. class Color:
  11. END = '\033[0m' # normal
  12. BOLD = '\033[1m' # bold
  13. RED = '\033[1;91m' # red
  14. GREEN = '\033[1;92m' # green
  15. ORANGE = '\033[1;93m' # orange
  16. BLUE = '\033[1;94m' # blue
  17. PURPLE = '\033[1;95m' # purple
  18. UNDERLINE = '\033[4m' # underline
  19. CYAN = '\033[1;96m' # cyan
  20. GREY = '\033[1;97m' # gray
  21. BR = '\033[1;97;41m' # background red
  22. BG = '\033[1;97;42m' # background green
  23. BY = '\033[1;97;43m' # background yellow

备份代码

  1. #########################################################################
  2. # File Name: query_mysql.py
  3. # Author: eight
  4. # Mail: 18847097110@163.com
  5. # Created Time: Thu 18 Apr 2024 11:12:26 AM CST
  6. #########################################################################
  7. #!/usr/bin/env python
  8. # -*- coding: utf-8 -*-
  9. import pymysql
  10. import configparser
  11. import os
  12. from datetime import datetime
  13. import DefaultColor
  14. import subprocess
  15. # 创建备份目录
  16. def mkdir():
  17. dir_path = os.getcwd()
  18. print("--------------------------------------------------------")
  19. print("当前脚本工作目录:", dir_path)
  20. mysql_backup_dir = "/opt/mysql_backup"
  21. print("--------------------------------------------------------")
  22. if not os.path.exists(mysql_backup_dir):
  23. os.makedirs(mysql_backup_dir)
  24. else:
  25. return f"数据库备份目录 '{mysql_backup_dir}' 已经存在,跳过创建"
  26. return "数据库备份目录:" + DefaultColor.Color.GREEN + mysql_backup_dir + DefaultColor.Color.END + " 创建成功"
  27. # 备份数据库
  28. def backup(mysql_backup_dir):
  29. config = configparser.ConfigParser()
  30. config.read("config.ini")
  31. # 获取配置信息
  32. host = config.get("MYSQL", "MYSQL_HOST")
  33. username = config.get("MYSQL", "MYSQL_USER")
  34. password = config.get("MYSQL", "MYSQL_PASSWORD")
  35. port = config.get("MYSQL", "MYSQL_PORT")
  36. db = config.get("MYSQL", "MYSQL_DB")
  37. current_datetime = datetime.now()
  38. formatted_datetime = current_datetime.strftime("%Y-%m-%d_%H-%M-%S")
  39. try:
  40. command = f'docker exec -it mysql-container /bin/bash -c "mysqldump -h {host} -u {username} -p{password} -P {port} -- {db} > {mysql_backup_dir}-{db}-{formatted_datetime}.sql"'
  41. subprocess.run(command, shell=True, check=True)
  42. except subprocess.CalledProcessError as e:
  43. print("Database backup failed:", e)
  44. return f"数据库:{db}备份完成: {mysql_backup_dir}-{db}-{formatted_datetime}.sql"
  45. if __name__ == '__main__':
  46. backup_dir = mkdir()
  47. print(backup_dir)
  48. backup = backup("/opt/mysql_backup")
  49. print(backup)

此代码如果是本地环境测试的话,逻辑是判断当前本地有没有存储备份数据的目录,没有则创建。

再利用subprocess执行mysqldump命令,按照日期生成.sql文件

效果

 因为是docker环境,所以判断当前目录是否存在,是判断的宿主机上的,所以此代码不是很严谨的代码,如果是本地部署的话,把mysqldump命令前面的  docker exec -it mysql-container /bin/bash -c  删除掉即可。

这样备份的脚本就实现了脚本预期效果:将数据库备份到指定的目录下,以日期区别sql文件

全量代码(读取配置和备份和查询)

  1. root@bogon:~ 2024-04-18 16:30:14# cat MysqlBackup.py
  2. #########################################################################
  3. # File Name: query_mysql.py
  4. # Author: eight
  5. # Mail: 18847097110@163.com
  6. # Created Time: Thu 18 Apr 2024 11:12:26 AM CST
  7. #########################################################################
  8. #!/usr/bin/env python
  9. # -*- coding: utf-8 -*-
  10. import pymysql
  11. import configparser
  12. import os
  13. from datetime import datetime
  14. import DefaultColor
  15. import subprocess
  16. # 读取mysql配置文件
  17. def mysql_config():
  18. config = configparser.ConfigParser()
  19. config.read("config.ini")
  20. # 获取配置信息
  21. host = config.get("MYSQL", "MYSQL_HOST")
  22. username = config.get("MYSQL", "MYSQL_USER")
  23. password = config.get("MYSQL", "MYSQL_PASSWORD")
  24. port = config.get("MYSQL", "MYSQL_PORT")
  25. db = config.get("MYSQL", "MYSQL_DB")
  26. print("--------------------------------------------------------")
  27. return f"主机:{host}\t用户名:{username}\t密码:{password}\t端口:{port}\t数据库:{db}"
  28. # 创建备份目录
  29. def mkdir():
  30. dir_path = os.getcwd()
  31. print("--------------------------------------------------------")
  32. print("当前脚本工作目录:", dir_path)
  33. mysql_backup_dir = "/opt/mysql_backup"
  34. print("--------------------------------------------------------")
  35. if not os.path.exists(mysql_backup_dir):
  36. os.makedirs(mysql_backup_dir)
  37. else:
  38. return f"数据库备份目录 '{mysql_backup_dir}' 已经存在,跳过创建"
  39. return "数据库备份目录:" + DefaultColor.Color.GREEN + mysql_backup_dir + DefaultColor.Color.END + " 创建成功"
  40. # 查询sql语句
  41. ##def select():
  42. # config = configparser.ConfigParser()
  43. # config.read("config.ini")
  44. #
  45. # # 获取配置信息
  46. # host = config.get("MYSQL", "MYSQL_HOST")
  47. # username = config.get("MYSQL", "MYSQL_USER")
  48. # password = config.get("MYSQL", "MYSQL_PASSWORD")
  49. # port = config.get("MYSQL", "MYSQL_PORT")
  50. # db = config.get("MYSQL", "MYSQL_DB")
  51. # # 创建mysql连接信息
  52. # conn = pymysql.connect(host=host, user=username, password=password, port=int(port), db=db)
  53. # cur = conn.cursor()
  54. # # 执行查询语句
  55. # cur.execute("use docker;")
  56. # cur.execute("select * from DockerImages;")
  57. # print("查询到的数据是:")
  58. # # 接收全部的返回结果行
  59. # result = cur.fetchall()
  60. # while True:
  61. # resp = cur.fetchone()
  62. # if resp is None:
  63. # break
  64. # # 关闭查询游标
  65. # cur.close()
  66. # # 提交
  67. # conn.commit()
  68. # # 关闭链接,释放计算机资源
  69. # conn.close()
  70. # return result
  71. # 备份数据库
  72. def backup(mysql_backup_dir):
  73. config = configparser.ConfigParser()
  74. config.read("config.ini")
  75. # 获取配置信息
  76. host = config.get("MYSQL", "MYSQL_HOST")
  77. username = config.get("MYSQL", "MYSQL_USER")
  78. password = config.get("MYSQL", "MYSQL_PASSWORD")
  79. port = config.get("MYSQL", "MYSQL_PORT")
  80. db = config.get("MYSQL", "MYSQL_DB")
  81. current_datetime = datetime.now()
  82. formatted_datetime = current_datetime.strftime("%Y-%m-%d_%H-%M-%S")
  83. try:
  84. command = f'docker exec -it mysql-container /bin/bash -c "mysqldump -h {host} -u {username} -p{password} -P {port} -- {db} > {mysql_backup_dir}-{db}-{formatted_datetime}.sql"'
  85. subprocess.run(command, shell=True, check=True)
  86. except subprocess.CalledProcessError as e:
  87. print("Database backup failed:", e)
  88. return f"数据库:{db}备份完成: {mysql_backup_dir}-{db}-{formatted_datetime}.sql"
  89. if __name__ == '__main__':
  90. #mysql_config = mysql_config()
  91. #print(mysql_config)
  92. backup_dir = mkdir()
  93. print(backup_dir)
  94. #sector = select()
  95. # 循环打印所有数据,如果此代码是封装在函数内部,那么使用return的话,只会输出第一条数据,所以要在外部调用
  96. #for row in sector:
  97. # print(row)
  98. backup = backup("/opt/mysql_backup")
  99. print(backup)
  100. root@bogon:~ 2024-04-18 16:30:18#
  101. root@bogon:~ 2024-04-18 16:30:32#
  102. root@bogon:~ 2024-04-18 16:30:32# cat MysqlBackup.py
  103. #########################################################################
  104. # File Name: query_mysql.py
  105. # Author: eight
  106. # Mail: 18847097110@163.com
  107. # Created Time: Thu 18 Apr 2024 11:12:26 AM CST
  108. #########################################################################
  109. #!/usr/bin/env python
  110. # -*- coding: utf-8 -*-
  111. import pymysql
  112. import configparser
  113. import os
  114. from datetime import datetime
  115. import DefaultColor
  116. import subprocess
  117. # 读取mysql配置文件
  118. def mysql_config():
  119. config = configparser.ConfigParser()
  120. config.read("config.ini")
  121. # 获取配置信息
  122. host = config.get("MYSQL", "MYSQL_HOST")
  123. username = config.get("MYSQL", "MYSQL_USER")
  124. password = config.get("MYSQL", "MYSQL_PASSWORD")
  125. port = config.get("MYSQL", "MYSQL_PORT")
  126. db = config.get("MYSQL", "MYSQL_DB")
  127. print("--------------------------------------------------------")
  128. return f"主机:{host}\t用户名:{username}\t密码:{password}\t端口:{port}\t数据库:{db}"
  129. # 创建备份目录
  130. def mkdir():
  131. dir_path = os.getcwd()
  132. print("--------------------------------------------------------")
  133. print("当前脚本工作目录:", dir_path)
  134. mysql_backup_dir = "/opt/mysql_backup"
  135. print("--------------------------------------------------------")
  136. if not os.path.exists(mysql_backup_dir):
  137. os.makedirs(mysql_backup_dir)
  138. else:
  139. return f"数据库备份目录 '{mysql_backup_dir}' 已经存在,跳过创建"
  140. return "数据库备份目录:" + DefaultColor.Color.GREEN + mysql_backup_dir + DefaultColor.Color.END + " 创建成功"
  141. # 查询sql语句
  142. def select():
  143. config = configparser.ConfigParser()
  144. config.read("config.ini")
  145. # 获取配置信息
  146. host = config.get("MYSQL", "MYSQL_HOST")
  147. username = config.get("MYSQL", "MYSQL_USER")
  148. password = config.get("MYSQL", "MYSQL_PASSWORD")
  149. port = config.get("MYSQL", "MYSQL_PORT")
  150. db = config.get("MYSQL", "MYSQL_DB")
  151. # 创建mysql连接信息
  152. conn = pymysql.connect(host=host, user=username, password=password, port=int(port), db=db)
  153. cur = conn.cursor()
  154. # 执行查询语句
  155. cur.execute("use docker;")
  156. cur.execute("select * from DockerImages;")
  157. print("查询到的数据是:")
  158. # 接收全部的返回结果行
  159. result = cur.fetchall()
  160. while True:
  161. resp = cur.fetchone()
  162. if resp is None:
  163. break
  164. # 关闭查询游标
  165. cur.close()
  166. # 提交
  167. conn.commit()
  168. # 关闭链接,释放计算机资源
  169. conn.close()
  170. return result
  171. # 备份数据库
  172. def backup(mysql_backup_dir):
  173. config = configparser.ConfigParser()
  174. config.read("config.ini")
  175. # 获取配置信息
  176. host = config.get("MYSQL", "MYSQL_HOST")
  177. username = config.get("MYSQL", "MYSQL_USER")
  178. password = config.get("MYSQL", "MYSQL_PASSWORD")
  179. port = config.get("MYSQL", "MYSQL_PORT")
  180. db = config.get("MYSQL", "MYSQL_DB")
  181. current_datetime = datetime.now()
  182. formatted_datetime = current_datetime.strftime("%Y-%m-%d_%H-%M-%S")
  183. try:
  184. command = f'docker exec -it mysql-container /bin/bash -c "mysqldump -h {host} -u {username} -p{password} -P {port} -- {db} > {mysql_backup_dir}-{db}-{formatted_datetime}.sql"'
  185. subprocess.run(command, shell=True, check=True)
  186. except subprocess.CalledProcessError as e:
  187. print("Database backup failed:", e)
  188. return f"数据库:{db}备份完成: {mysql_backup_dir}-{db}-{formatted_datetime}.sql"
  189. if __name__ == '__main__':
  190. mysql_config = mysql_config()
  191. print(mysql_config)
  192. backup_dir = mkdir()
  193. print(backup_dir)
  194. sector = select()
  195. #循环打印所有数据,如果此代码是封装在函数内部,那么使用return的话,只会输出第一条数据,所以要在外部调用
  196. for row in sector:
  197. print(row)
  198. backup = backup("/opt/mysql_backup")
  199. print(backup)

效果

优化

  1. #########################################################################
  2. # File Name: query_mysql.py
  3. # Author: eight
  4. # Mail: 18847097110@163.com
  5. # Created Time: Thu 18 Apr 2024 11:12:26 AM CST
  6. #########################################################################
  7. #!/usr/bin/env python
  8. # -*- coding: utf-8 -*-
  9. import pymysql
  10. import configparser
  11. import os
  12. from datetime import datetime
  13. import DefaultColor
  14. import subprocess
  15. # 读取mysql配置文件
  16. def mysql_config():
  17. config = configparser.ConfigParser()
  18. config.read("config.ini")
  19. # 获取配置信息
  20. host = config.get("MYSQL", "MYSQL_HOST")
  21. username = config.get("MYSQL", "MYSQL_USER")
  22. password = config.get("MYSQL", "MYSQL_PASSWORD")
  23. port = config.get("MYSQL", "MYSQL_PORT")
  24. db = config.get("MYSQL", "MYSQL_DB")
  25. print("--------------------------------------------------------")
  26. return {
  27. "host": host,
  28. "username": username,
  29. "password": password,
  30. "port": port,
  31. "db": db
  32. }
  33. # 创建备份目录
  34. def mkdir():
  35. dir_path = os.getcwd()
  36. print("--------------------------------------------------------")
  37. print("当前脚本工作目录:", dir_path)
  38. mysql_backup_dir = "/opt/mysql_backup"
  39. print("--------------------------------------------------------")
  40. if not os.path.exists(mysql_backup_dir):
  41. os.makedirs(mysql_backup_dir)
  42. else:
  43. return f"数据库备份目录 '{mysql_backup_dir}' 已经存在,跳过创建"
  44. return "数据库备份目录:" + DefaultColor.Color.GREEN + mysql_backup_dir + DefaultColor.Color.END + " 创建成功"
  45. # 查询sql语句
  46. def select():
  47. mysql_connect_info = mysql_config()
  48. # 创建mysql连接信息
  49. conn = pymysql.connect(host=mysql_connect_info["host"],
  50. user=mysql_connect_info["username"],
  51. password=mysql_connect_info["password"],
  52. port=int(mysql_connect_info["port"]),
  53. db=mysql_connect_info["db"])
  54. cur = conn.cursor()
  55. # 执行查询语句
  56. cur.execute("use docker;")
  57. cur.execute("select * from DockerImages;")
  58. print("查询到的数据是:")
  59. # 接收全部的返回结果行
  60. result = cur.fetchall()
  61. while True:
  62. resp = cur.fetchone()
  63. if resp is None:
  64. break
  65. # 关闭查询游标
  66. cur.close()
  67. # 提交
  68. conn.commit()
  69. # 关闭链接,释放计算机资源
  70. conn.close()
  71. return result
  72. # 备份数据库
  73. def backup(mysql_backup_dir):
  74. # 获取配置信息
  75. current_datetime = datetime.now()
  76. formatted_datetime = current_datetime.strftime("%Y-%m-%d_%H-%M-%S")
  77. mysql_connect_info = mysql_config()
  78. try:
  79. command = f'docker exec -it mysql-container /bin/bash -c "mysqldump -h {mysql_connect_info["host"]} -u {mysql_connect_info["username"]} -p{mysql_connect_info["password"]} -P {mysql_connect_info["port"]} -- {mysql_connect_info["db"]} > {mysql_backup_dir}-{mysql_connect_info["db"]}-{formatted_datetime}.sql"'
  80. subprocess.run(command, shell=True, check=True)
  81. except subprocess.CalledProcessError as e:
  82. print("Database backup failed:", e)
  83. return f'数据库:{mysql_connect_info["db"]}备份完成: {mysql_backup_dir}-{mysql_connect_info["db"]}-{formatted_datetime}.sql'
  84. if __name__ == '__main__':
  85. backup_dir = mkdir()
  86. print(backup_dir)
  87. sector = select()
  88. #循环打印所有数据,如果此代码是封装在函数内部,那么使用return的话,只会输出第一条数据,所以要在外部调用
  89. for row in sector:
  90. print(row)
  91. backup = backup("/opt/mysql_backup")
  92. print(backup)

将配置文件信息以字典的方式返回

在查询函数时,使用相应的键来访问这些值

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/467616
推荐阅读
相关标签
  

闽ICP备14008679号