對(duì)python 通過ssh訪問數(shù)據(jù)庫(kù)的實(shí)例詳解
通常,為了安全性,數(shù)據(jù)庫(kù)只允許通過ssh來訪問。例如:mysql數(shù)據(jù)庫(kù)放在服務(wù)器A上,只允許數(shù)據(jù)庫(kù)B來訪問,這時(shí),我們需要用機(jī)器C去訪問數(shù)據(jù)庫(kù),就需要用C通過ssh連接B,再訪問A。
通過pymysql連接mysql:
import pymysql
from sshtunnel import SSHTunnelForwarder
with SSHTunnelForwarder(
(sshServerB_ip, sshServerB_port), # B機(jī)器的配置
ssh_password=sshServerB_pwd,
ssh_username=sshServerB_usr,
remote_bind_address=(databaseA_ip, databaseA_port)) as server: # A機(jī)器的配置
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()
以下是自己進(jìn)行事務(wù)管理,并使用peewee框架:
from peewee import *
from playhouse.db_url import connect
from sshtunnel import SSHTunnelForwarder
server = SSHTunnelForwarder(
(sshServerB_ip, sshServerB_port), # B機(jī)器的配置
ssh_password=sshServerB_pwd,
ssh_username=sshServerB_usr,
remote_bind_address=(databaseA_ip, databaseA_port)) # A機(jī)器的配置
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()
以上這篇對(duì)python 通過ssh訪問數(shù)據(jù)庫(kù)的實(shí)例詳解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python學(xué)習(xí)筆記之錯(cuò)誤和異常及訪問錯(cuò)誤消息詳解
這篇文章主要介紹了Python學(xué)習(xí)筆記之錯(cuò)誤和異常及訪問錯(cuò)誤消息,結(jié)合實(shí)例形式分析了Python錯(cuò)誤和異常及訪問錯(cuò)誤消息try...except語句相關(guān)使用技巧,需要的朋友可以參考下2019-08-08
在keras中獲取某一層上的feature map實(shí)例
今天小編就為大家分享一篇在keras中獲取某一層上的feature map實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-01-01
python類中super()和__init__()的區(qū)別
這篇文章主要介紹了python類中super()和__init__()的區(qū)別,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2016-10-10
python深度學(xué)習(xí)tensorflow入門基礎(chǔ)教程示例
這篇文章主要為大家介紹了python深度學(xué)習(xí)tensorflow入門基礎(chǔ)教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
python中的load、loads實(shí)現(xiàn)反序列化示列
這篇文章主要介紹python中的load、loads實(shí)現(xiàn)反序列化,在python自動(dòng)化中,我們傳遞一些參數(shù)是需要從文件中讀取過來的,讀取過來的字典并非python對(duì)象數(shù)據(jù)類型而是string類型,下面來看詳情內(nèi)容吧2021-10-10
Numpy之random.randint產(chǎn)生隨機(jī)整數(shù)方式
這篇文章主要介紹了Numpy之random.randint產(chǎn)生隨機(jī)整數(shù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12

