LoginSignup
11
11

More than 3 years have passed since last update.

PythonでSSHトンネリングしてAmazon Aurora MySQLに繋ぐ

Last updated at Posted at 2018-08-20

はじめに

業務でsshを使って踏み台のAmazon EC2サーバーに繋いでそこからAmazon Aurora MySQLに繋いでSQLを実行するということをやっているのですが、いちいちコマンドを打つのが面倒なので、Pythonでその辺の処理を自動化したいと思います。

Requirements

mysql-connector-python
sshtunnel

以上のモジュールをpipを使ってPyPIから取ってきます。

$ pip install mysql-connector-python sshtunnel

Example code

import mysql.connector
from sshtunnel import SSHTunnelForwarder

SSH_BASTION_ADDRESS = '**.**.***.**'  # ここに踏み台のEC2サーバーのIPアドレスを入れる
SSH_PORT = 22
SSH_USER = 'ec2-user'
SSH_PKEY_PATH = os.path.expanduser('~/key.pem')  # ここにsshで繋ぐときのキーファイルを指定する
MYSQL_HOST = 'foo.bar.ap-northeast-1.rds.amazonaws.com'  # ここにAmazon Aurora MySQLのアドレスを書く
MYSQL_PORT = 3306
MYSQL_USER = 'root'
MYSQL_PASS = 'foo'
MYSQL_DB = 'db'


if __name__ == '__main__':
    with SSHTunnelForwarder(
        (SSH_BASTION_ADDRESS, SSH_PORT),
        ssh_pkey=SSH_PKEY_PATH,
        ssh_username=SSH_USER,
        remote_bind_address=(MYSQL_HOST, MYSQL_PORT),
        local_bind_address=('0.0.0.0', MYSQL_PORT),
    ):
        connection = mysql.connector.connect(
            host='127.0.0.1',
            port=MYSQL_PORT,
            user=MYSQL_USER,
            passwd=MYSQL_PASS,
            db=MYSQL_DB,
            charset='utf8'
        )
        pass  # 何かクエリを叩いたりする
        connection.close()
11
11
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
11
11