mariadb python sshtunnel不启动服务器给出凭据

wtlkbnrh  于 7个月前  发布在  Python
关注(0)|答案(2)|浏览(103)

所以我试着让mysql-connector-pythonsshtunnel一起工作

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_addresslocal_bind_host等。都被设置为错误,说:

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

尽管我的代码中确实有tunnel.start()
我做了检查,我的服务器是可见的其他程序(例如。DataGrip),我不知道问题出在哪里。

pieyvz9o

pieyvz9o1#

您正在使用with SSHTunnelForwarder的上下文管理器,这意味着它将在退出范围时关闭连接。将cur = mydb.cursor放在上下文管理器作用域中可以解决这个问题。

7cjasjjr

7cjasjjr2#

或者,您可以删除上下文管理器,但请记住关闭隧道,因为您正在显式启动它。

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

相关问题