MySql 跳板机 python连接方法及配置

import pymysql
from sshtunnel import SSHTunnelForwarder
#可能需要安装上面的包

#跳板机
host_jump=跳板机ip
port_jump=跳板机port
user_name_jump=跳板机用户名
ssh_password=跳板机密码

#数据库
host_mysql=数据库ip
port_mysql=数据库port
user_name_mysql=数据库用户名
password_mysql=数据库密码
database=数据库名称
local_bind_port=22 #本地端口自行定义

server = SSHTunnelForwarder(
    (host_jump, int(port_jump)),  # 跳板机的配置
    ssh_password=ssh_password,
    ssh_username=user_name_jump,
    remote_bind_address=(host_mysql, int(port_mysql)))  # 数据库服务器的配置

server.start() #启动server

connection = pymysql.connect(host='127.0.0.1', port=server.local_bind_port, 
			user=user_name_mysql, password=password_mysql, database=database,
			charset="utf8", cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()
cursor.execute('select * from test_db where id=1')
data=cursor.fetchall()

#注意关闭
conn.close()
server.close()

print(data)

reference

https://blog.csdn.net/github_38294021/article/details/79695426

https://blog.csdn.net/zyq_victory/article/details/88722467

猜你喜欢

转载自blog.csdn.net/weixin_48185819/article/details/123847782