SSH ポートフォワードで MySQL サーバにログインするときのメモ

localhostMySQL サーバへの接続が許可されていない。192.0.2.2 は MySQL サーバへの接続の許可されている。
そんなときに localhost から MySQL サーバへログインする方法。

                        • +
localhost SSH, MySQL client
                        • +
|
                        • +
192.0.2.2 SSH server
                        • +
|
                        • +
192.0.2.3 MySQL server
                        • +

SSH ポートフォワードを有効にする

localhost にて以下のコマンドを実行する。

% ssh -N -L 13306:192.0.2.3:3306 192.0.2.2

localhost の 13306 番ポートを 192.0.2.2 を介して 192.0.2.3 の 3306 番ポートに転送する。

MySQL サーバにログインする

同じく localhost にて以下のコマンドを実行する。

% mysql -h127.0.0.1 -P13306
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 39
Server version: 5.1.49-1ubuntu8.1 (Ubuntu)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

ホストは 192.0.2.3 ではなく 127.0.0.1、ポートはポートフォワードを行っている 13306 番を指定する。
ホストに localhost を指定すると接続できない。TCP/IP を使用せずに Unix ソケットを使うのが原因。

% mysql -hlocalhost -P13306    
ERROR 1045 (28000): Access denied for user 'yamamucho'@'localhost' (using password: NO)