場景:本地--跳轉機--mysql服務器
分兩步:1.通過sshtunnel登陸跳轉機;2.創建數據庫連接。
import pymysql
from sshtunnel import SSHTunnelForwarder
with SSHTunnelForwarder(
('*.*.*.*', 11690), # 指定ssh登錄的跳轉機的address,端口號
ssh_username="***", # 跳轉機的用戶
ssh_pkey="/Users/.ssh/id_rsa", #私鑰路徑
ssh_private_key_password="***", #密碼(電腦開機密碼)
remote_bind_address=('*.*.*.*', 3306)) as server: # mysql服務器的address,端口號
conn = pymysql.connect(host='127.0.0.1', # 此處必須是是127.0.0.1
port=server.local_bind_port,
user='**', #數據庫用戶名
passwd='**', #數據庫密碼
db='**' #數據庫名稱)
cursor = conn.cursor()
# 使用 execute() 方法執行 SQL 查詢
cursor.execute("SELECT VERSION();")
# 使用 fetchone() 方法獲取單條數據.
data = cursor.fetchone()
print("Database version : %s " % data)
# 關閉數據庫連接
cursor.close()