mattintosh note

どこかのエンジニアモドキの備忘録

127.0.0.1が許可されていないMySQLサーバにポートフォワーディングで接続する

とある場所で動いている MySQL のデータベースの調査して欲しいと言われたのでいつも通り SSH でポート転送をかけてローカルの mysql コマンドを使おうと思ったら 127.0.0.1 は許可されてないよって言われた。

ERROR 1130 (HY000): Host '127.0.0.1' is not allowed to connect to this MySQL server

とりあえずサーバの中から直接入ってみるとホストを見ると localhost しかないのでソケット通信しか受け付けないようだ。

MySQL Client

mysql> select user, host from mysql.user where user = 'root';
+---------+----------------------------+
| user    | host                       |
+---------+----------------------------+
| root    | localhost                  |
+---------+----------------------------+

さて、SSH のポート転送はソケット対応してたかな、と man を読み返してみたらちゃんと対応してた。

man ssh

-L [bind_address:]port:host:hostport
-L [bind_address:]port:remote_socket ❶
-L local_socket:host:hostport
-L local_socket:remote_socket ❷
        Specifies that connections to the given TCP port or Unix socket
        on the local (client) host are to be forwarded to the given host
        and port, or Unix socket, on the remote side.  This works by
        allocating a socket to listen to either a TCP port on the local
        side, optionally bound to the specified bind_address, or to a
        Unix socket.  Whenever a connection is made to the local port or
        socket, the connection is forwarded over the secure channel, and
        a connection is made to either host port hostport, or the Unix
        socket remote_socket, from the remote machine.

        Port forwardings can also be specified in the configuration file.
        Only the superuser can forward privileged ports.  IPv6 addresses
        can be specified by enclosing the address in square brackets.

        By default, the local port is bound in accordance with the
        GatewayPorts setting.  However, an explicit bind_address may be
        used to bind the connection to a specific address.  The
        bind_address of ``localhost'' indicates that the listening port
        be bound for local use only, while an empty address or `*' indi-
        cates that the port should be available from all interfaces.

リモートソケットに接続する方法は二種類あるけどローカルは環境に応じてポート番号で使い分けたいので❶の「ローカルポート→リモートソケット」の方法を使う。

Terminal

$ ssh -L 13306:/var/lib/mysql/mysql.sock db-1
        ----- -------------------------
          ^               ^
          |               |
          |               `-- リモートソケットパス
          |
          `-- ローカルポート 

コンフィグで設定しておく場合は LocalForward でローカルポートとリモートソケットのパスを書いておく。

ssh_config

Host db-1
    HostName xxx.xxx.xxx.xxx
    LocalForward 13306 /var/lib/mysql/mysql.sock

Host db-2
    HostName yyy.yyy.yyy.yyy
    LocalForward 23306 /var/lib/mysql/mysql.sock

あとはクライアントでローカルポートを指定すれば SSH を経由してリモートのソケットまで飛ばしてくれる。

Terminal

$ mysql -u root -p -P 13306 --protocol tcp
$ mysql -u root -p -P 13306 -h 127.0.0.1