对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设计】。

相关文章

python调用动态链接库的基本过程详解

python调用动态链接库的基本过程详解

动态链接库在Windows中为.dll文件,在linux中为.so文件。以linux平台为例说明python调用.so文件的使用方法。 本例中默认读者已经掌握动态链接库的生成方法,如果不...

在Python中使用列表生成式的教程

列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。 举个例子,要生成list [1, 2, 3, 4, 5, 6, 7...

使用实现XlsxWriter创建Excel文件并编辑

使用实现XlsxWriter创建Excel文件并编辑

之前操作Excel使用过其他的方式,针对Excel的写入来说,使用过xlwt模块,也直接使用过win32com接口。如果说哪个最能够发挥Excel的威力,那么肯定是win32com接口实...

python中zip()方法应用实例分析

本文实例分析了python中zip()方法的应用。分享给大家供大家参考,具体如下: 假设有一个集合set, 需要对set中的每个元素指定一个唯一的id,从而组建成一个dict结构。 这个...

Python数学形态学实例分析

Python数学形态学实例分析

本文实例讲述了Python数学形态学。分享给大家供大家参考,具体如下: 一 原始随机图像 1、代码 import numpy as np import matplotlib.pypl...