• 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:32# 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. host = config.get("MYSQL", "MYSQL_HOST")
    46. username = config.get("MYSQL", "MYSQL_USER")
    47. password = config.get("MYSQL", "MYSQL_PASSWORD")
    48. port = config.get("MYSQL", "MYSQL_PORT")
    49. db = config.get("MYSQL", "MYSQL_DB")
    50. # 创建mysql连接信息
    51. conn = pymysql.connect(host=host, user=username, password=password, port=int(port), db=db)
    52. cur = conn.cursor()
    53. # 执行查询语句
    54. cur.execute("use docker;")
    55. cur.execute("select * from DockerImages;")
    56. print("查询到的数据是:")
    57. # 接收全部的返回结果行
    58. result = cur.fetchall()
    59. while True:
    60. resp = cur.fetchone()
    61. if resp is None:
    62. break
    63. # 关闭查询游标
    64. cur.close()
    65. # 提交
    66. conn.commit()
    67. # 关闭链接,释放计算机资源
    68. conn.close()
    69. return result
    70. # 备份数据库
    71. def backup(mysql_backup_dir):
    72. config = configparser.ConfigParser()
    73. config.read("config.ini")
    74. # 获取配置信息
    75. host = config.get("MYSQL", "MYSQL_HOST")
    76. username = config.get("MYSQL", "MYSQL_USER")
    77. password = config.get("MYSQL", "MYSQL_PASSWORD")
    78. port = config.get("MYSQL", "MYSQL_PORT")
    79. db = config.get("MYSQL", "MYSQL_DB")
    80. current_datetime = datetime.now()
    81. formatted_datetime = current_datetime.strftime("%Y-%m-%d_%H-%M-%S")
    82. try:
    83. 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"'
    84. subprocess.run(command, shell=True, check=True)
    85. except subprocess.CalledProcessError as e:
    86. print("Database backup failed:", e)
    87. return f"数据库:{db}备份完成: {mysql_backup_dir}-{db}-{formatted_datetime}.sql"
    88. if __name__ == '__main__':
    89. mysql_config = mysql_config()
    90. print(mysql_config)
    91. backup_dir = mkdir()
    92. print(backup_dir)
    93. sector = select()
    94. #循环打印所有数据,如果此代码是封装在函数内部,那么使用return的话,只会输出第一条数据,所以要在外部调用
    95. for row in sector:
    96. print(row)
    97. backup = backup("/opt/mysql_backup")
    98. 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)

  • 相关阅读:
    react this.setState接收参数 。写成Promise形式。以及async/await和Promise的区别
    SpringBoot 入门
    深度学习——深度学习计算二
    使用 TiDB Lightning 恢复 S3 兼容存储上的备份数据
    策略模式应用(内窥镜项目播放不同种类的视频)
    java计算机毕业设计个性化产品服务管理系统源码+mysql数据库+系统+lw文档+部署
    DevOps|从特拉斯辞职风波到研发效能中的不靠谱人干的荒唐事
    使用MySQL
    【MySQL】聊聊order by 是如何排序的
    1Panel应用推荐:Uptime Kuma
  • 原文地址:https://blog.csdn.net/eighters/article/details/137949006