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

相关文章

python3 面向对象__类的内置属性与方法的实例代码

0.object类源码 class object: """ The most base type """ def __delattr__(self, *args, **kwa...

Python 网络编程之TCP客户端/服务端功能示例【基于socket套接字】

本文实例讲述了Python 网络编程之TCP客户端/服务端功能。分享给大家供大家参考,具体如下: demo.py(TCP客户端): import socket def main():...

Flask框架Jinjia模板常用语法总结

Flask框架Jinjia模板常用语法总结

本文实例总结了Flask框架Jinjia模板常用语法。分享给大家供大家参考,具体如下: 1. 变量表示 {{ argv }} 2. 赋值操作 {% set links =...

详解pyinstaller selenium python3 chrome打包问题

详解pyinstaller selenium python3 chrome打包问题

今天打包selenium一个简单的请求,打完包本机运行exe没有问题,换台机器就闪退,非常蛋疼找了半天原因。 下面简述下,防止踩坑,如果闪退十有八九是浏览器版本跟浏览器插件对不上。 首先...

解决Spyder中图片显示太小的问题

最近在做机器学习的作业,需要画决策树。在Spyder中把代码跑了一遍,发现决策树出现在了Spyder的console中,而且图片很小,那些字体都叠在一起。网上搜了一圈好像也没找到解决方案...