LoginSignup
2
3

More than 5 years have passed since last update.

jupyter つかって、windows で、tunnel して、mysql のデータをとってくる

Last updated at Posted at 2016-11-11

jupyter から、ssh でトンネルして、mysql データベースを操作可能です。便利です。(jupyter でなくてももちろんよいです。)

anaconda を普段使っていて、jupyter も使うような人が対象です。
paramiko と、sshtunnel をインストールします。conda-forge にありますので、conda だけでインストールできます。
pandas の import は結構時間かかるので、読み込み時間を計測しています。

# port 番号も適宜変更してください。
# ssh の port は、88099 
# remote の port 3306 mysqlのつもり 
# local  の port 3307 なんでもいいですが、覚えやすいように、3306 + 1 

import os,sys,re,platform
import pymysql
%time import pandas as pd
import codecs

from sshtunnel import SSHTunnelForwarder

server = SSHTunnelForwarder(
    ('ログイン先',88099),
     ssh_username="ユーザ名",
     ssh_password="パスワード",
     ssh_pkey="/Users/hoge/.ssh/hoge_key など",
     remote_bind_address=('127.0.0.1', 3306),
     local_bind_address=('127.0.0.1', 3307)
)

server.start()


# ここで、適当に処理、下記は、show tables して、pandas に放り込んでいます。

conn = pymysql.connect(host='127.0.0.1',port=3307,
db='データベース名', user='データベースユーザ', passwd='データベース',
charset="utf8")
xdf = pd.read_sql('show tables', con=conn)
conn.close()

server.stop()
2
3
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
2
3