LoginSignup
6
7

More than 5 years have passed since last update.

PythonからMySQLへの接続でcaching_sha2_passwordのエラーが出た場合

Last updated at Posted at 2018-09-18

Pythonを使ってMySQLへ接続しようとしたら、認証方式のエラーで拒否されたので対策しました。

バージョン:

mysql Ver 8.0.12 for osx10.13 on x86_64 (Homebrew)caching_sha2_passwordのエラー

エラーの原因は認証方式

Pythonから接続しようして表示されたエラーは次のようなものです。

Traceback (most recent call last):

...略...

_mysql_connector.MySQLInterfaceError: Authentication plugin 'caching_sha2_password' cannot be loaded: dlopen(/Users/sato/miniconda3/lib/plugin/caching_sha2_password.so, 2): image not found

During handling of the above exception, another exception occurred:
...略...

Authentication plugin 'caching_sha2_password' cannot be loaded:

ということなので認証方式「caching_sha2_password」にエラーがあるらしい。

「caching_sha2_password」はMySQL 8.0からサポートされた認証方式で、デフォルトになっています。

しかし、Pythonから接続するドライバが対応していない。

そこで、pythonが対応している従来の認証方式「mysql_native_password」に変更することにしました。

MySQLで特定のユーザだけ認証方式を変更する

MySQLにルートでログインして、ユーザごとにどの認証を使っているか表示してみます。

mysql> select user, plugin from user;
+------------------+-----------------------+
| user             | plugin                |
+------------------+-----------------------+
| mysql.infoschema | caching_sha2_password |
| mysql.session    | caching_sha2_password |
| mysql.sys        | caching_sha2_password |
| root             | caching_sha2_password |
| sato             | caching_sha2_password |
+------------------+-----------------------+
5 rows in set (0.00 sec)

ユーザ名「sato」からのみPythonに接続できればいいので変更するのはユーザ「sato」だけ、rootはそのままにします。

次のコマンドで変更しました。

mysql> alter user 'sato'@'localhost' identified WITH mysql_native_password by 'パスワード';

反映されたか確認。

mysql> select user, plugin from user;
+------------------+-----------------------+
| user             | plugin                |
+------------------+-----------------------+
| mysql.infoschema | caching_sha2_password |
| mysql.session    | caching_sha2_password |
| mysql.sys        | caching_sha2_password |
| root             | caching_sha2_password |
| sato             | mysql_native_password |
+------------------+-----------------------+
5 rows in set (0.00 sec)

これで、Pythonから接続できるようになりました。

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7