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

yipeiwu_com5年前Python基础

通常,为了安全性,数据库只允许通过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访问数据库的实例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python for循环中的陷阱详解

Python for循环中的陷阱详解

前言 Python 中的 for 循环和其他语言中的 for 循环工作方式是不一样的,今天就带你深入了解 Python 的 for 循环,看看它是如何工作的,以及它为什么按照这种方式工作...

web.py在SAE中的Session问题解决方法(使用mysql存储)

这段时间一直想尝试着在SAE中使用Python,初步选择了Web.py框架做为开发框架,但是可怜SAE上的资料少的可怜,有点问题基本上解决不了,今天解决一个Session在Session...

Python基础之文件读取的讲解

with open(filename) as fp: dataMat = [] for line in fp.readlines(): # fp.rea...

Python异常的检测和处理方法

捕获异常 # 对数字变量使用append操作 a = 123 a.apppend(4) 执行这个程序时,会抛出: AttributeError: 'int' object h...

python获取Pandas列名的几种方法

 获取DataFrame虽然是一个比较简单的操作,但是有时候到手边就是写不出来,所以在这里总结记录一下: 1.链表推倒式 data = pd.read_csv('data/...