通過sshtunner連接數據庫:
代碼如下:
import pymysql
from sshtunnel import SSHTunnelForwarder
with SSHTunnelForwarder(
('123.56.12.1',22), # 指定ssh登錄的跳轉機的address,端口號
ssh_username='user', # 跳轉機的用戶
ssh_password='pwd123',# 跳板機用戶的密碼
remote_bind_address=('123.56.199.198',3306)) as server: # mysql服務器的address,端口號
conn = pymysql.connect(host='127.0.0.1', # 此處必須是是127.0.0.1
port=server.local_bind_port,
user='dbuser', # 數據庫用戶名
passwd='dbpwd123', # 數據庫密碼
charset='utf8',
db='dbname',# 數據庫名稱
autocommit=True)# 如果修改數據庫自動提交
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute("SELECT * FROM table where name='xiaoming';")
result=cursor.fetchall()
print(result)
cursor.close()#關閉游標
conn.close()#關閉連接
