Skip to content

sqlalchmy 通过ssh链接数据库

66 字小于 1 分钟

2024-12-01

from sshtunnel import SSHTunnelForwarder
from sqlalchemy import create_engine

# 开启ssh通道
server =  SSHTunnelForwarder(
     (ssh_host, ssh_port),
     ssh_password=ssh_password,
     ssh_username=ssh_user,
     remote_bind_address=(mysql_host, 3306))

server.start()


engine = create_engine('mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(mysql_user,
                                                                                    mysql_password,
                                                                                    '127.0.0.1',
                                                                                    server.local_bind_port,
                                                                                    mysql_db))

# 执行很多数据
# ........

server.stop()