【问题标题】:MYSQL and Python (via ssh)MYSQL 和 Python(通过 ssh)
【发布时间】:2018-04-14 15:42:16
【问题描述】:

这可能是尝试使用 python 在远程机器上运行 mysql 查询的重复问题。 我为此使用 pymysql 和 SSHTunnelForwarder。

mysqldb 位于不同的服务器上(192.168.10.13 和端口 5555)。

我正在尝试使用以下 sn-p:

with SSHTunnelForwarder(
        (host, ssh_port),
        ssh_username = ssh_user,
        ssh_password = ssh_pass,
        remote_bind_address=('127.0.0.1', 5555)) as server:

    with pymysql.connect("192.168.10.13", user, password, port=server.local_bind_port) as connection:
            cursor = connection.cursor()
            output = cursor.execute("select * from billing_cdr limit 1")
            print output

这是正确的做法吗?

我看到以下错误:

sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway

还有其他推荐的库吗?

【问题讨论】:

    标签: python python-2.7 pymysql


    【解决方案1】:

    经过一番挖掘后发现这是可行的。

    with SSHTunnelForwarder(
            ("192.168.10.13", 22),
            ssh_username = ssh_user,
            ssh_password = ssh_pass,
            remote_bind_address=('127.0.0.1', 5555)) as server:
    
        with pymysql.connect('127.0.0.1', user, password, port=server.local_bind_port) as connection:
                output = connection.execute("select * from db.table limit 1")
                print output
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      conn = MySQLdb.connect(
          host=host,
          port=port,
          user=username,
          passwd=password,
          db=database
          charset='utf8',)
      cur = conn.cursor()
      cur.execute("select * from billing_cdr limit 1")
      rows = cur.fetchall()
      for row in rows:
          a=row[0]
          b=row[1]
      conn.close()
      

      【讨论】:

      猜你喜欢
      • 2014-02-18
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      • 2018-04-05
      相关资源
      最近更新 更多