对python 通过ssh访问数据库的实例详解
通常,为了安全性,数据库只允许通过ssh来访问。例如:mysql数据库放在服务器A上,只允许数据库B来访问,这时,我们需要用机器C去访问数据库,就需要用C通过ssh连接B,再访问A。
通过pymysql连接mysql:
importpymysql
fromsshtunnelimportSSHTunnelForwarder
withSSHTunnelForwarder(
(sshServerB_ip,sshServerB_port),#B机器的配置
ssh_password=sshServerB_pwd,
ssh_username=sshServerB_usr,
remote_bind_address=(databaseA_ip,databaseA_port))asserver:#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('callstoredProcedure')
db_connect.commit()
以下是自己进行事务管理,并使用peewee框架:
frompeeweeimport*
fromplayhouse.db_urlimportconnect
fromsshtunnelimportSSHTunnelForwarder
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))
'''
yourcodetooperatethedatabaseA
'''
server.close()
以上这篇对python通过ssh访问数据库的实例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
热门推荐
7 简短的二胎祝福语
10 简短霸气女儿生日 祝福语
11 祝福语高考小众诗句简短
12 元旦祝福语20秒简短
13 老师过年祝福语大全 简短
14 一生祝福语简短
15 产检祝福语简短霸气
16 朋友店开张祝福语简短
17 生日爱情祝福语大全简短
18 朋友女儿生日祝福语 简短