对python 通过ssh访问数据库的实例详解

(编辑:jimmy 日期: 2024/9/28 浏览:2)

通常,为了安全性,数据库只允许通过ssh来访问。例如:mysql数据库放在服务器A上,只允许数据库B来访问,这时,我们需要用机器C去访问数据库,就需要用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()

以下是自己进行事务管理,并使用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访问数据库的实例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

一句话新闻

微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。