对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判断列表是否已排序的各种方法及其性能分析

声明 本文基于Python2.7语言,给出判断列表是否已排序的多种方法,并在作者的Windows XP主机(Pentium G630 2.7GHz主频2GB内存)上对比和分析其性能表现...

Python匿名函数及应用示例

本文实例讲述了Python匿名函数及应用。分享给大家供大家参考,具体如下: lambda关键词能创建?型匿名函数。这种函数得名于省略了def声明函数的标准步骤。 代码如下:...

使用CodeMirror实现Python3在线编辑器的示例代码

使用CodeMirror实现Python3在线编辑器的示例代码

一、编写页面 主要是引入相关的css文件和js文件,这里采用简单插入link和script标签的形式。 <!DOCTYPE html> <html lang="en...

Python使用正则表达式过滤或替换HTML标签的方法详解

本文实例讲述了Python使用正则表达式过滤或替换HTML标签的方法。分享给大家供大家参考,具体如下: python正则表达式关键内容: python正则表达式转义符: . 匹配除换行符...

简单解析Django框架中的表单验证

我们的搜索示例仍然相当地简单,特别从数据验证方面来讲;我们仅仅只验证搜索关键值是否为空。 然后许多HTML表单包含着比检测值是否为空更为复杂的验证。 我们都有在网站上见过类似以下的错误提...