业务场景:
1.平时学习的时候连接数据库的方法是直接使用pymysql这个模块直接根据ip和端口等进行数据库的连接;但是在实际工作中数据库的连接可能还要通过一个跳板机才能连接到对应的数据库;
2.查阅了一下资料大概是这么个连接流程,navicat要想连接到数据库则需要先连接到SSH服务器,再通过SSH服务去连接到数据库,而这个SSH服务器则称为跳板机;
3. 在python中可以通过模块sshtunnel来进行连接
from sshtunnel import SSHTunnelForwarder
import pymysql
server = SSHTunnelForwarder(
#跳板机IP,跳板机端口号
('ssh_IP','ssh_port'),
ssh_username='testuser',
ssh_password='pwd',
#如果验证方式是公钥的话可以使用下面的参数
ssh_pkey='F:/Python_file/Test_work/config/testuser', #私钥文件位置
ssh_private_key_password='****', #私钥密码(通行短语)
remote_bind_address=('remote_IP',3306) #远程数据库的IP和端口
)
server.start()
#host必须为127.0.0.1,代表本机(堡垒机),user和passwd填的是远程数据库的账号密码
conn = pymysql.connect(host='127.0.0.1',port=server.local_bind_port,user='remote_user',passwd='remote_pwd',db='data_base')
#创建游标
cur = conn.cursor()
#执行sql语句
cur.execute('select * from vstore_order_base_info where id=73')
#返回所有结果
res = cur.fetchall()
print(res)
#关闭游标
cur.close()
#关闭连接
conn.close()
#关闭服务
server.close()
个人使用的封装
from sshtunnel import SSHTunnelForwarder
from common.get_config import Get_config
import pymysql,json
#连接信息
ssh = json.loads(Get_config().get_data("mysql","ssh_connect"))
local = json.loads(Get_config().get_data("mysql","local_connect"))
class mysql_connetc():
def __ssh(self,addr,ssh_username,ssh_private_key_password,remote_bind_address,user,passwd):
server = SSHTunnelForwarder(
eval(addr),
ssh_username=ssh_username,
ssh_private_key_password=ssh_private_key_password,
#私钥文件位置
ssh_pkey='F:/Python_file/Test_work/config/testuser',
remote_bind_address=eval(remote_bind_address))
return server,user,passwd
#通过ssh连接数据库
def connect_ssh(self,db,sql,ssh_data=ssh,console_num=0):
"""
:param console_num 查询结果数据量,默认输出全部
:param ssh_data 连接ssh的数据,以解包的形式传入
:param sql sql语句
:param db 连接的数据库
"""
server,user,passwd = self.__ssh(**ssh_data)
server.start()
conn = pymysql.connect(host='127.0.0.1',port=server.local_bind_port,user=user,passwd=passwd,db=db)
#创建游标
cur = conn.cursor()
#执行sql
cur.execute(sql)
#输出结果,console_num控制输出的查询结果条数,默认为输出全部
if console_num == 0:
res = cur.fetchall()
elif console_num == 1:
res = cur.fetchone()
else:
res = cur.fetchmany(console_num)
#关闭服务
cur.close()
conn.close()
server.close()
return res
#直接通过IP进行数据库连接
def connect_db(self,db,sql,console_num=0,connect_data=local):
host = connect_data["host"]
port = int(connect_data["port"])
user = connect_data["user"]
passwd = connect_data["passwd"]
conn = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db)
cur = conn.cursor()
cur.execute(sql)
# 输出结果,console_num控制输出的查询结果条数,默认为输出全部
if console_num == 0:
res = cur.fetchall()
elif console_num == 1:
res = cur.fetchone()
else:
res = cur.fetchmany(console_num)
# 关闭服务
cur.close()
conn.close()
return res
Get_config函数中的数据格式