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

yipeiwu_com6年前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设计】。

相关文章

Pycharm取消py脚本中SQL识别的方法

Pycharm取消py脚本中SQL识别的方法

Pycharm默认可以识别py脚本中的SQL语句,本身很不错,但当SQL拼接时就显示的代码特别难看,找了好久,终于知道怎么关闭SQL识别功能了。 如下图,把勾去掉就可以了。 以上这篇P...

python中enumerate函数遍历元素用法分析

本文实例讲述了python中enumerate函数遍历元素用法。分享给大家供大家参考,具体如下: enumerate函数用于遍历序列中的元素以及它们的下标 示例代码如下: i = 0...

python判断输入日期为第几天的实例

如下所示: # -*- coding: utf-8 -*- # 简述:要求输入某年某月某日 # 提问:求判断输入日期是当年中的第几天? def which_day(year,mont...

使用Python写一个量化股票提醒系统

使用Python写一个量化股票提醒系统

大家在没有阅读本文之前先看下python的基本概念, Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。 Python由Guido van Rossum于1989年底...

pytorch 调整某一维度数据顺序的方法

在pytorch中,Tensor是以引用的形式存在的,故而并不能直接像python交换数据那样 a = torch.Tensor(3,4) a[0],a[1] = a[1],a[0]...