利用 SSH tunnels 連線至內部 MySQL Server

TONY
TONY
Aug 22, 2017 · 2 min read

使用過 SSH tunnel 的人都知道他是如此的方便,除了常用的putty或pietty,我更愛用的是MobaXterm,而且光看這張圖就大致了解 SSH tunnels 在做什麼了

你可以使用上述的程市來綁定本地端的port,來達到操作遠端 server 的方式。但如果要在程式碼中達到以上的效果呢?


在 python 中,有個套件叫做 sshtunnel,真的可以很簡單地幫你做到上面的方法

安裝

pip install paramiko sshtunnel MySQL-python

依照官方提供的圖,很清楚可以看到其中的做法

對於實作的code也是非常的簡單

import sshtunnel
import MySQLdb
# 開啟一個通道穿越REMOTE SERVER直到REMOTE PRIVATE SERVER
# 並且將他和local端的port綁定
server = sshtunnel.SSHTunnelForwarder(
('remote_host', 22),
ssh_username="user_name",
ssh_password="user_pw",
remote_bind_address=('remote_private_server', 3306)
)
server.start()
# 使用已和local端綁定的port 去遠端連線MySQL
conn = MySQLdb.connect(host='127.0.0.1',
port=server.local_bind_port,
user='mysql_user',
passwd='mysql_pw',
db='db_name')
server.stop()

如此,就可以很輕易地建立起 connection 了

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade