通常,為了安全性,數據庫只允許通過ssh來訪問。例如:mysql數據庫放在服務器A上,只允許數據庫B來訪問,這時,我們需要用機器C去訪問數據庫,就需要用C通過ssh連接B,再訪問A。
通過pymysql連接mysql:
import pymysqlfrom sshtunnel import SSHTunnelForwarderwith SSHTunnelForwarder(  (sshServerB_ip, sshServerB_port), # B機器的配置  ssh_password=sshServerB_pwd,  ssh_username=sshServerB_usr,  remote_bind_address=(databaseA_ip, databaseA_port)) as server: # A機器的配置 db_connect = pymysql.connect(host='127.0.0.1', # 此處必須是是127.0.0.1         port=server.local_bind_port,         user=databaseA_usr,         passwd=databaseA_pwd,         db=databaseA_db) cur = db_connect.cursor() cur.execute('call storedProcedure') db_connect.commit()以下是自己進行事務管理,并使用peewee框架:
from peewee import *from playhouse.db_url import connectfrom sshtunnel import SSHTunnelForwarderserver = SSHTunnelForwarder(  (sshServerB_ip, sshServerB_port), # B機器的配置  ssh_password=sshServerB_pwd,  ssh_username=sshServerB_usr,  remote_bind_address=(databaseA_ip, databaseA_port)) # A機器的配置server.start()destination_lib = connect('mysql://%s:%s@127.0.0.1:%d/%s' % (databaseA_usr, databaseA_pwd, server.local_bind_port, databaseA_db))'''your code to operate the databaseA'''server.close()以上這篇對python 通過ssh訪問數據庫的實例詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答