对python 通过ssh访问数据库的实例详解
作者:Howard93wws 时间:2024-01-16 07:32:12
通常,为了安全性,数据库只允许通过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()
来源:https://blog.csdn.net/u011318721/article/details/79310947
标签:python,ssh,数据库
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java正则表达式验证工具类
2022-03-03 12:47:01
详解用Python为直方图绘制拟合曲线的两种方法
2021-06-15 23:58:08
![](https://img.aspxhome.com/file/2023/0/67350_0s.jpg)
利用Python如何生成hash值示例详解
2022-02-28 23:29:25
关于换行和回车的图文小结
2023-07-17 14:41:37
![](https://img.aspxhome.com/file/2023/6/132326_0s.jpg)
python对绑定事件的鼠标、按键的判断实例
2021-05-20 03:12:58
python 矢量数据转栅格数据代码实例
2022-06-12 03:40:14
Python操作Access数据库基本步骤分析
2024-01-18 22:32:20
在Recordset对象中查询记录的方法
2008-11-20 16:51:00
导航与搜索合并的可能性
2009-09-27 12:06:00
![](https://img.aspxhome.com/file/UploadPic/20099/27/nav_search-33s.png)
Linux安装卸载Mysql数据库
2011-01-29 16:45:00
![](https://img.aspxhome.com/file/UploadPic/20111/29/2011129165230857s.jpg)
CSS Hack 汇总快查
2007-11-06 11:48:00
python绘制规则网络图形实例
2021-08-31 02:28:28
详解PHP中的mb_detect_encoding函数使用方法
2023-11-14 19:48:45
Python标准库pathlib操作目录和文件
2021-08-18 02:24:57
![](https://img.aspxhome.com/file/2023/8/101598_0s.jpg)
Go语言编程中判断文件是否存在是创建目录的方法
2024-05-21 10:22:02
Python数据类型之Tuple元组实例详解
2023-02-17 05:24:01
基于Python os模块常用命令介绍
2023-09-09 01:53:43
![](https://img.aspxhome.com/file/2023/2/121912_0s.png)
Python 作为小程序后端的三种实现方法(推荐)
2023-03-30 09:26:05
![](https://img.aspxhome.com/file/2023/1/101621_0s.jpg)
js 获取后台的字段 改变 checkbox的被选中的状态 代码
2024-04-22 22:33:40
python实现自动解数独小程序
2023-03-28 12:15:19