1

This may be a repeated question of attempting to run a mysql query on a remote machine using python. Im using pymysql and SSHTunnelForwarder for this.

The mysqldb is located on different server (192.168.10.13 and port 5555).

Im trying to use the following snippet:

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

Is this the correct approach ?

I see the following error:

sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway

Also is there any other recommended library to use ?

2 Answers 2

1

Found this to be working after some digging.

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
Sign up to request clarification or add additional context in comments.

Comments

0

you can do it like this:

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()

2 Comments

I need to establish the connection via ssh only. The server would not allow a standard connect to mysql.
ok, you can follow this page to do it. blog.imdst.com/python-shi-yong-sshsui-dao-lian-jie-mysql

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.