{"id":147,"date":"2023-10-25T14:50:09","date_gmt":"2023-10-25T06:50:09","guid":{"rendered":"https:\/\/www.liaoxinghui.com\/?p=147"},"modified":"2023-10-27T13:55:16","modified_gmt":"2023-10-27T05:55:16","slug":"%e7%9c%81%e6%97%b6%e7%9c%81%e5%bf%83python%e5%a4%87%e4%bb%bd%e6%95%b0%e6%8d%ae%e5%ba%93","status":"publish","type":"post","link":"https:\/\/www.liaoxinghui.com\/?p=147","title":{"rendered":"\u7528Python\u5b9a\u65f6\u5907\u4efdMysql"},"content":{"rendered":"<h3>\u6211\u4eec\u7ecf\u5e38\u4f1a\u6d89\u53ca\u5907\u4efdmysql\uff0c\u4e0b\u9762\u6709\u51e0\u79cd\u7528python\u5b9a\u65f6\u5907\u4efd\u7684\u51e0\u4efd\u4ee3\u7801\uff0c\u4ee3\u7801\u5206\u62103\u79cd\uff0c\u5206\u522b\u662f\u5355\u673a\u6307\u5b9a\u5355\u5e93\u7684\uff0c\u5355\u673a\u591a\u5e93\u7684\uff0c\u591a\u673a\u591a\u5e93\u7684\uff0c\u5f04\u597d\u4ee5\u540ecron\u91cc\u6dfb\u52a0\u4e0b\u81ea\u52a8\u4efb\u52a1\u5c31\u53ef\u4ee5\u4e86<\/h3>\n<ul>\n\n<li>\u5355\u673a\u6307\u5b9a\u6570\u636e\u5e93\u7684<\/li>\n<\/ul>\n<pre><code>#!\/usr\/bin\/python\n# -*- coding: UTF-8 -*-\n\n# \u5bfc\u5165\u6240\u9700\u6a21\u5757\nimport warnings\nimport pymysql\nimport os\nimport time\nimport logging\n\n# \u6570\u636e\u5e93\u8fde\u63a5\u4fe1\u606f\n\nmysql_host = &quot;\u6570\u636e\u5e93\u5730\u5740&quot;\nmysql_user = &quot;\u6570\u636e\u5e93\u7528\u6237&quot;\nmysql_pwd = &quot;\u5bc6\u7801&quot;\nmysql_port = 3306\nmysql_charset = &quot;utf8&quot;\n\n# \u5907\u4efd\u65f6\u95f4\u548c\u8def\u5f84\nnew_date = time.strftime(&quot;%Y%m%d%H%M%S&quot;)\nback_path = &quot;\/home\/dataBasebak\/wordpress\/&quot;  # \u6307\u5b9a\u5907\u4efd\u8def\u5f84\n\n# \u65e5\u5fd7\u8def\u5f84\nlog_path = &quot;\/var\/log\/mysql_backup\/&quot;\nif not os.path.exists(log_path):\n    os.makedirs(log_path)\n\n# \u8bbe\u7f6e\u65e5\u5fd7\u8bb0\u5f55\nlogging.basicConfig(level=logging.INFO, format=&#039;%(asctime)s - %(name)s - %(levelname)s - %(message)s&#039;)\nlogger = logging.getLogger(__name__)\n\n# \u8bbe\u7f6e\u65e5\u5fd7\u6587\u4ef6\u8def\u5f84\nhandler_success = logging.FileHandler(log_path + &#039;success.log&#039;)\nhandler_success.setLevel(logging.INFO)\n\nhandler_error = logging.FileHandler(log_path + &#039;error.log&#039;)\nhandler_error.setLevel(logging.ERROR)\n\n# \u8bbe\u7f6e\u65e5\u5fd7\u683c\u5f0f\nformatter = logging.Formatter(&#039;%(asctime)s - %(name)s - %(levelname)s - %(message)s&#039;)\nhandler_success.setFormatter(formatter)\nhandler_error.setFormatter(formatter)\n\n#\u6dfb\u52a0\u65e5\u5fd7\u5904\u7406\u5668\nlogger.addHandler(handler_success)\nlogger.addHandler(handler_error)\n\ntry:\n    # \u5982\u679c\u5907\u4efd\u8def\u5f84\u4e0d\u5b58\u5728\uff0c\u5219\u521b\u5efa\n    if not os.path.exists(back_path):\n        os.makedirs(back_path)\n\n    # \u8fde\u63a5\u6570\u636e\u5e93\n    conn = pymysql.connect(\n        host=mysql_host,\n        user=mysql_user,\n        passwd=mysql_pwd,\n        db=&#039;mysql&#039;,\n        port=mysql_port,\n        charset=mysql_charset\n    )\n    cur = conn.cursor()\n\n    # \u6307\u5b9a\u5907\u4efd\u7684\u6570\u636e\u5e93\u540d\n    db_name = &quot;wordpress&quot;\n    logger.info(f&#039;\u5f53\u524d\u7684\u6570\u636e\u5e93\u540d\u662f:{db_name}&#039;)\n\n    # \u6307\u5b9a\u5907\u4efd\u6587\u4ef6\u7684\u8def\u5f84\u548c\u540d\u79f0\n    path = back_path + db_name + new_date + &quot;.sql&quot;\n    logger.info(f&#039;\u5907\u4efd\u6587\u4ef6\u7684\u8def\u5f84\u548c\u540d\u79f0\u662f:{path}&#039;)\n\n    # \u6267\u884c\u5907\u4efd\u547d\u4ee4\n    os.system(&quot;mysqldump -h%s -u%s -p%s %s &gt; %s&quot; % (mysql_host, mysql_user, mysql_pwd, db_name, path))\n    logger.info(&#039;\u5907\u4efd\u6210\u529f&#039;)\n\n    cur.close()  # \u5173\u95ed\u6e38\u6807\n    conn.close()  # \u91ca\u653e\u6570\u636e\u5e93\u8d44\u6e90\n\nexcept Exception as e:\n    logger.error(&quot;\u5907\u4efd\u5931\u8d25&quot;, exc_info=True)<\/code><\/pre>\n<ul>\n\n<li>\u5355\u673a\u591a\u5e93\u7684<\/li>\n<\/ul>\n<pre><code>#!\/usr\/bin\/python\n# -*- coding: UTF-8 -*-\n\n# \u5bfc\u5165\u6240\u9700\u6a21\u5757\nimport warnings\nimport pymysql\nimport os\nimport time\nimport logging\n\n# \u6570\u636e\u5e93\u8fde\u63a5\u4fe1\u606f\nmysql_host = &quot;\u6570\u636e\u5e93\u5730\u5740&quot;\nmysql_user = &quot;\u6570\u636e\u5e93\u7528\u6237&quot;\nmysql_pwd = &quot;\u5bc6\u7801&quot;\nmysql_port = 3306\nmysql_charset = &quot;utf8&quot;\n\n# \u5907\u4efd\u65f6\u95f4\u548c\u8def\u5f84\nnew_date = time.strftime(&quot;%Y%m%d%H%M%S&quot;)\nback_path = &quot;\/home\/dataBasebak\/&quot;  \n\n# \u65e5\u5fd7\u8def\u5f84\nlog_path = &quot;\/var\/log\/mysql_backup\/&quot;\nif not os.path.exists(log_path):\n    os.makedirs(log_path)\n\n# \u8bbe\u7f6e\u65e5\u5fd7\u8bb0\u5f55\nlogging.basicConfig(level=logging.INFO, format=&#039;%(asctime)s - %(name)s - %(levelname)s - %(message)s&#039;)\nlogger = logging.getLogger(__name__)\n\n# \u8bbe\u7f6e\u65e5\u5fd7\u6587\u4ef6\u8def\u5f84\nhandler_success = logging.FileHandler(log_path + &#039;success.log&#039;)\nhandler_success.setLevel(logging.INFO)\n\nhandler_error = logging.FileHandler(log_path + &#039;error.log&#039;)\nhandler_error.setLevel(logging.ERROR)\n\n# \u8bbe\u7f6e\u65e5\u5fd7\u683c\u5f0f\nformatter = logging.Formatter(&#039;%(asctime)s - %(name)s - %(levelname)s - %(message)s&#039;)\nhandler_success.setFormatter(formatter)\nhandler_error.setFormatter(formatter)\n\n# \u6dfb\u52a0\u65e5\u5fd7\u5904\u7406\u5668\nlogger.addHandler(handler_success)\nlogger.addHandler(handler_error)\n\ntry:\n    # \u5982\u679c\u5907\u4efd\u8def\u5f84\u4e0d\u5b58\u5728\uff0c\u5219\u521b\u5efa\n    if not os.path.exists(back_path):\n        os.makedirs(back_path)\n\n    # \u8fde\u63a5\u6570\u636e\u5e93\n    conn = pymysql.connect(\n        host=mysql_host,\n        user=mysql_user,\n        passwd=mysql_pwd,\n        db=&#039;mysql&#039;,\n        port=mysql_port,\n        charset=mysql_charset\n    )\n    cur = conn.cursor()\n    cur.execute(&#039;show databases&#039;)  # \u67e5\u8be2\u51fa\u6240\u6709\u6570\u636e\u5e93\n    data = cur.fetchall()  # \u67e5\u8be2\u51fa\u6765\uff0c\u5e76\u8d4b\u503c data\n\n    for db_names in data:\n        for db_name in db_names:\n            if db_name in [&#039;information_schema&#039;, &#039;performance_schema&#039;, &#039;mysql&#039;]:\n                continue\n            if not os.path.exists(back_path + db_name):\n                os.makedirs(back_path + db_name)\n            path = back_path + db_name + &quot;\/&quot; + new_date + &quot;.sql&quot;  # \u6570\u636e\u5e93\u5907\u4efd\u8def\u5f84\n            logger.info(f&#039;\u5907\u4efd\u6587\u4ef6\u7684\u8def\u5f84\u548c\u540d\u79f0\u662f:{path}&#039;)\n            os.system(&quot;mysqldump -h%s -u%s -p%s %s &gt; %s&quot; % (mysql_host, mysql_user, mysql_pwd, db_name, path))\n            logger.info(&#039;\u5907\u4efd\u6210\u529f&#039;)\n\n    cur.close()  # \u5173\u95ed\u6e38\u6807\n    conn.close()  # \u91ca\u653e\u6570\u636e\u5e93\u8d44\u6e90\n\nexcept Exception as e:\n    logger.error(&quot;\u5907\u4efd\u5931\u8d25&quot;, exc_info=True)\n<\/code><\/pre>\n<ul>\n\n<li>\u591a\u673a\u591a\u5e93\u5c31\u7528\u8fd9\u4e2a<\/li>\n<\/ul>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># coding=utf-8\n\"\"\"\n@Time \uff1a 2022\/10\/25 17:16\n@Author \uff1a Taering\n@File \uff1aback_mysql_many_servers.py\n@IDE \uff1aPyCharm\n@DESC :\n\"\"\"\n\nimport pymysql\nimport os\nimport time\nimport logging\n\n# \u6570\u636e\u5e93\u8fde\u63a5\u4fe1\u606f\nmysql_servers = [\n    {\n        \"host\": \"\u6570\u636e\u5e93A\u7684\u5730\u5740\",\n        \"user\": \"\u6570\u636e\u5e93A\u7684\u7528\u6237\u540d\",\n        \"pwd\": \"\u6570\u636e\u5e93A\u7684\u5bc6\u7801\",\n        \"port\": 3306,\n        \"charset\": \"utf8\"\n    },\n    {\n        \"host\": \"\u6570\u636e\u5e93B\u7684\u5730\u5740\",\n        \"user\": \"\u6570\u636e\u5e93B\u7684\u7528\u6237\u540d\",\n        \"pwd\": \"\u6570\u636e\u5e93B\u7684\u5bc6\u7801\",\n        \"port\": 3306,\n        \"charset\": \"utf8\"\n    },\n]\n\n# \u5907\u4efd\u65f6\u95f4\u548c\u8def\u5f84\nnew_date = time.strftime(\"%Y%m%d%H%M%S\")\nback_path = \"\/SqlData\/dataBasebak\/\"\n\n# \u65e5\u5fd7\u8def\u5f84\nlog_path = \"\/var\/log\/mysql_backup\/\"\nif not os.path.exists(log_path):\n    os.makedirs(log_path)\n\n# \u8bbe\u7f6e\u65e5\u5fd7\u8bb0\u5f55\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nlogger = logging.getLogger(__name__)\n\n# \u8bbe\u7f6e\u65e5\u5fd7\u6587\u4ef6\u8def\u5f84\nhandler_success = logging.FileHandler(log_path + 'success.log')\nhandler_success.setLevel(logging.INFO)\n\nhandler_error = logging.FileHandler(log_path + 'error.log')\nhandler_error.setLevel(logging.ERROR)\n\n# \u8bbe\u7f6e\u65e5\u5fd7\u683c\u5f0f\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler_success.setFormatter(formatter)\nhandler_error.setFormatter(formatter)\n\n# \u6dfb\u52a0\u65e5\u5fd7\u5904\u7406\u5668\nlogger.addHandler(handler_success)\nlogger.addHandler(handler_error)\n\nfor server in mysql_servers:\n    try:\n        # \u5982\u679c\u5907\u4efd\u8def\u5f84\u4e0d\u5b58\u5728\uff0c\u5219\u521b\u5efa\n        if not os.path.exists(back_path + server['host']):\n            os.makedirs(back_path + server['host'])\n\n        # \u8fde\u63a5\u6570\u636e\u5e93\n        conn = pymysql.connect(\n            host=server['host'],\n            user=server['user'],\n            passwd=server['pwd'],\n            db='mysql',\n            port=server['port'],\n            charset=server['charset']\n        )\n        cur = conn.cursor()\n        cur.execute('show databases')  # \u67e5\u8be2\u51fa\u6240\u6709\u6570\u636e\u5e93\n        data = cur.fetchall()  # \u67e5\u8be2\u51fa\u6765\uff0c\u5e76\u8d4b\u503c data\n\n        for db_names in data:\n            for db_name in db_names:\n                logger.info(f'\u5f53\u524d\u7684\u6570\u636e\u5e93\u540d\u662f:{db_name}')\n                if db_name in ['information_schema', 'performance_schema', 'mysql', 'sys']:\n                    continue\n                if not os.path.exists(back_path + server['host'] + \"\/\" + db_name):\n                    os.makedirs(back_path + server['host'] + \"\/\" + db_name)\n                path = back_path + server['host'] + \"\/\" + db_name + \"\/\" + new_date + \".sql\"  # \u6570\u636e\u5e93\u5907\u4efd\u8def\u5f84\n                print(path)\n\n                logger.info(f'\u5907\u4efd\u6587\u4ef6\u7684\u8def\u5f84\u548c\u540d\u79f0\u662f:{path}')\n                os.system(\n                    \"mysqldump -h%s -u%s -p%s %s &gt; %s\" % (server['host'], server['user'], server['pwd'], db_name, path))\n                logger.info('\u5907\u4efd\u6210\u529f')\n\n        cur.close()  # \u5173\u95ed\u6e38\u6807\n        conn.close()  # \u91ca\u653e\u6570\u636e\u5e93\u8d44\u6e90\n\n    except Exception as e:\n        logger.error(\"\u5907\u4efd\u5931\u8d25\", exc_info=True)\n\n# \u5220\u96647\u5929\u524d\u7684\u5907\u4efd\uff0c\u81ea\u5df1\u770b\u7740\u6539\u5220\u9664\u65f6\u95f4\uff0c\u6216\u8005\u4e0d\u5220\u9664\u4e5f\u53ef\u4ee5\nfor server in mysql_servers:\n    try:\n        # \u83b7\u53d6\u5907\u4efd\u8def\u5f84\n        path = back_path + server['host']\n        # \u83b7\u53d6\u6240\u6709\u6570\u636e\u5e93\u76ee\u5f55\n        db_dirs = os.listdir(path)\n        for db_dir in db_dirs:\n            # \u83b7\u53d6\u6570\u636e\u5e93\u5907\u4efd\u76ee\u5f55\n            db_path = os.path.join(path, db_dir)\n            # \u83b7\u53d6\u6240\u6709\u5907\u4efd\u6587\u4ef6\n            files = os.listdir(db_path)\n            for file in files:\n                # \u83b7\u53d6\u5907\u4efd\u6587\u4ef6\u5b8c\u6574\u8def\u5f84\n                file_path = os.path.join(db_path, file)\n                # \u83b7\u53d6\u5907\u4efd\u6587\u4ef6\u521b\u5efa\u65f6\u95f4\n                file_ctime = os.path.getctime(file_path)\n                # \u83b7\u53d6\u5f53\u524d\u65f6\u95f4\n                now_time = time.time()\n                # \u5982\u679c\u5907\u4efd\u6587\u4ef6\u521b\u5efa\u65f6\u95f4\u8d85\u8fc77\u5929\uff0c\u5220\u9664\u5907\u4efd\u6587\u4ef6\n                if now_time - file_ctime &gt; 7 * 24 * 60 * 60:\n                    os.remove(file_path)\n                    logger.info(f'\u5220\u96647\u5929\u524d\u7684\u5907\u4efd\u6587\u4ef6:{file_path}')\n    except Exception as e:\n        logger.error(\"\u5220\u96647\u5929\u524d\u7684\u5907\u4efd\u5931\u8d25\", exc_info=True)\n<\/pre>\n<h3>\u8fdc\u7a0b\u8c03\u7528\uff0c\u6216\u8005\u5728mysql\u672c\u5730\u90fd\u53ef\u4ee5\uff0c\u6700\u597d\u7684\u65b9\u6cd5\u662f\u5f00\u4e00\u4e2a\u53ea\u8bfb\u7684\u8d26\u53f7\u53ea\u5141\u8bb8\u7279\u5b9aIP\u94fe\u63a5\uff0c\u7136\u540e\u6bcf\u5929\u8fdb\u884c\u5907\u4efd\uff0c\u8fd9\u6837\u5b89\u5168\u4e00\u4e9b\uff0c\u5373\u4fbf\u662f\u4e3b\u7ad9\u6302\u4e86\u4e5f\u662f\u635f\u5931\u6709\u9650\uff0c\u5982\u679c\u4f60\u7528\u4e3b\u4ece\u7684\u8bdd\u662f\u5b9e\u65f6\u7684\uff0c\u90a3\u6837\u66f4\u597d\u4e00\u4e9b<\/h3>\n<p>\u4f60\u8981\u662f\u89c9\u5f97\u6ca1\u6709\u65f6\u6548\u6027\uff0c\u5c31\u53bb\u770b\u770b<a href=\"https:\/\/www.liaoxinghui.com\/149.html\">mysql\u4e3b\u4ece\u540c\u6b65\u548c\u534a\u540c\u6b65<\/a><\/p>","protected":false},"excerpt":{"rendered":"<p>\u6211\u4eec\u7ecf\u5e38\u4f1a\u6d89\u53ca\u5907\u4efdmysql\uff0c\u4e0b\u9762\u6709\u51e0\u79cd\u7528python\u5b9a\u65f6\u5907\u4efd\u7684\u51e0\u4efd\u4ee3\u7801\uff0c\u4ee3\u7801\u5206\u62103\u79cd\uff0c\u5206\u522b\u662f\u5355\u673a\u6307\u5b9a\u5355\u5e93\u7684\uff0c\u5355\u673a\u591a\u5e93\u7684\uff0c\u591a\u673a\u591a\u5e93\u7684\uff0c\u5f04\u597d &hellip;<\/p>","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5,10],"tags":[28],"class_list":["post-147","post","type-post","status-publish","format-standard","hentry","category-python","category-10","tag-python"],"views":582,"_links":{"self":[{"href":"https:\/\/www.liaoxinghui.com\/index.php?rest_route=\/wp\/v2\/posts\/147","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.liaoxinghui.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.liaoxinghui.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.liaoxinghui.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.liaoxinghui.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=147"}],"version-history":[{"count":6,"href":"https:\/\/www.liaoxinghui.com\/index.php?rest_route=\/wp\/v2\/posts\/147\/revisions"}],"predecessor-version":[{"id":204,"href":"https:\/\/www.liaoxinghui.com\/index.php?rest_route=\/wp\/v2\/posts\/147\/revisions\/204"}],"wp:attachment":[{"href":"https:\/\/www.liaoxinghui.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=147"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.liaoxinghui.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=147"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.liaoxinghui.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=147"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}