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

通常,为了安全性,数据库只允许通过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访问数据库的实例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值