對python 通過ssh訪問數(shù)據(jù)庫的實例詳解
通常,為了安全性,數(shù)據(jù)庫只允許通過ssh來訪問。例如:mysql數(shù)據(jù)庫放在服務(wù)器A上,只允許數(shù)據(jù)庫B來訪問,這時,我們需要用機器C去訪問數(shù)據(jù)庫,就需要用C通過ssh連接B,再訪問A。
通過pymysql連接mysql:
import pymysql
from sshtunnel import SSHTunnelForwarder
with 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()
以下是自己進行事務(wù)管理,并使用peewee框架:
from peewee import *
from playhouse.db_url import connect
from sshtunnel import SSHTunnelForwarder
server = 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訪問數(shù)據(jù)庫的實例詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python WXPY實現(xiàn)微信監(jiān)控報警功能的代碼
本篇文章主要介紹了Python WXPY實現(xiàn)微信監(jiān)控報警功能的代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
Numpy中創(chuàng)建數(shù)組的9種方式小結(jié)
本文主要介紹了Numpy中創(chuàng)建數(shù)組的9種方式小結(jié),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03
解決Jupyter NoteBook輸出的圖表太小看不清問題
這篇文章主要介紹了解決Jupyter NoteBook輸出的圖表太小看不清問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Python使用ftplib實現(xiàn)簡易FTP客戶端的方法
這篇文章主要介紹了Python使用ftplib實現(xiàn)簡易FTP客戶端的方法,實例分析了ftplib模塊相關(guān)設(shè)置與使用技巧,需要的朋友可以參考下2015-06-06
python實現(xiàn)中文轉(zhuǎn)換url編碼的方法
這篇文章主要介紹了python實現(xiàn)中文轉(zhuǎn)換url編碼的方法,結(jié)合實例形式分析了Python針對中文的gbk與utf-8編碼轉(zhuǎn)換的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2016-06-06

