如何在python中通过ssh连接到mysql localhost?

时间:2020-10-09 14:58:46

标签: python mysql ssh

我正在尝试使用python上的ssh连接到localhost mysql上的数据库。使用终端和PyChar的数据源,获得与数据库的连接。

with SSHTunnelForwarder(
    (ssh_host, ssh_port),
    ssh_username=ssh_user,
    ssh_password=ssh_pass,
    remote_bind_address=('127.0.0.1', 3306),
    logger=create_logger(loglevel=1)) as tunnel:

with pymysql.connect(host='127.0.0.1',
                     user=db_user,
                     passwd=db_pass,
                     db=db_name,
                     port=tunnel.local_bind_port) as connection:

    print("!!!!!!!!!CONNECTED!!!!!!!!!!!")
    output = connection.execute("select * from BD.b_catalog limit 1")
    print(output)

我正在尝试使用SSHTunnelForwarder进行连接,但没有任何反应。我看不到带有连接消息的珍贵印刷品。

记录器:

2020-10-09 17:19:39,977| WAR | MainThrea/0964@sshtunnel | Could not read SSH configuration file: ~/.ssh/config
2020-10-09 17:19:39,977| INF | MainThrea/0992@sshtunnel | 0 keys loaded from agent
2020-10-09 17:19:39,977| INF | MainThrea/1040@sshtunnel | 0 keys loaded from host directory
2020-10-09 17:19:39,977| INF | MainThrea/0910@sshtunnel | Connecting to gateway: 83.220.172.208:22 as user 'root'
2020-10-09 17:19:39,977| DEB | MainThrea/0915@sshtunnel | Concurrent connections allowed: True
2020-10-09 17:19:39,977| DEB | MainThrea/1367@sshtunnel | Trying to log in with password: *************
2020-10-09 17:19:40,155| INF | Srv-38583/1386@sshtunnel | Opening tunnel: 0.0.0.0:38583 <> 127.0.0.1:3306
2020-10-09 17:19:41,160| TRA |  Thread-3/0349@sshtunnel | #1 <-- ('127.0.0.1', 58390) to ('127.0.0.1', 3306) was rejected by the SSH server
2020-10-09 17:19:41,160| ERR |  Thread-3/0384@sshtunnel | Could not establish connection from ('127.0.0.1', 38583) to remote side of the tunnel
2020-10-09 17:19:41,160| INF | MainThrea/1407@sshtunnel | Shutting down tunnel ('0.0.0.0', 38583)
2020-10-09 17:19:41,221| WAR |  Thread-1/1819@transport | Success for unrequested channel! [??]
2020-10-09 17:19:41,260| INF | Srv-38583/1392@sshtunnel | Tunnel: 0.0.0.0:38583 <> 127.0.0.1:3306 released
2020-10-09 17:19:41,260| DEB | MainThrea/1421@sshtunnel | Transport is closed

错误消息:

...
packet_header = self._read_bytes(4)
  File "/home/kvando/PycharmProjects/py_scrapy/venv/lib/python3.8/site-packages/pymysql/connections.py", line 698, in _read_bytes
    raise err.OperationalError(
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')

0 个答案:

没有答案