python sshtunnel 未启动给定凭据的服务器

问题描述 投票:0回答:2

所以我正在努力让

mysql-connector-python
sshtunnel

合作
with SSHTunnelForwarder(('192.168.0.1', 22), ssh_username='pi', ssh_password='*********', remote_bind_address=('localhost', 3306)) as tunnel:
    tunnel.start()
    mydb = mysql.connector.connect(host="localhost",
                                   user='Mashu',
                                   password='*******',
                                   port=tunnel.local_bind_port,
                                   db='mysql')

print(mydb)
cur = mydb.cursor()
cur.execute('USE mysql')
print(cur.execute('SELECT * FROM user'))

它似乎执行得很顺利,但是当我想创建光标时它说

mysql.connector.errors.OperationalError: MySQL Connection not available.

我进一步调查,发现值连接到本地绑定,所以

local_bind_address
local_bind_host
等都设置为错误,说:

Server is not started. Please .start() first!

即使我的代码中有

tunnel.start()

我确实检查过,我的服务器对于其他程序(例如 DataGrip)是可见的,我不知道问题出在哪里。

python mysql mariadb ssh-tunnel mysql-connector-python
2个回答
1
投票

您正在使用带有

with SSHTunnelForwarder
的上下文管理器,这意味着它将在退出范围时关闭连接。将
cur = mydb.cursor
放入上下文管理器范围内将解决该问题。


0
投票

或者,您可以删除上下文管理器,但请记住关闭隧道,因为您是明确启动它的。

tunnel = get_ssh_tunnel(host, int(port), ssh_config)
                tunnel.start()
                conn = #connection settings
                # do stuff
                tunnel.close()
                conn.close()

© www.soinside.com 2019 - 2024. All rights reserved.