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

相关文章

24式加速你的Python(小结)

24式加速你的Python(小结)

一,分析代码运行时间 第1式,测算代码运行时间 平凡方法 快捷方法(jupyter环境) 第2式,测算代码多次运行平均时间 平凡方法 快捷方法(jupyter环境) 第3式,按调...

python3中rank函数的用法

网上存在这么一个例子 obj = pd.Series([7,-5,7,4,2,0,4]) obj.rank() 输出为: 0 6.5 1 1.0 2 6.5 3 4....

利用Python查看目录中的文件示例详解

前言 我们在日常开发中,经常会遇到一些关于文件的操作,例如,实现查看目录内容的功能。类似Linux下的tree命令。统计目录下指定后缀文件的行数。 功能是将目录下所有的文件路径存入lis...

selenium python浏览器多窗口处理代码示例

本文主要研究的是selenium python浏览器多窗口处理的相关内容,分享了操作实例代码,具体如下: #!/usr/bin/python # -*- coding: utf-8...

对python3中pathlib库的Path类的使用详解

对python3中pathlib库的Path类的使用详解

用了很久的os.path,今天发现竟然还有这么好用的库,记录下来以便使用。 1.调用库 from pathlib import 2.创建Path对象 p = Path('D:...