abhishek nair
abhishek nair

Reputation: 345

MYSQL and Python (via ssh)

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 ?

Upvotes: 1

Views: 2884

Answers (2)

abhishek nair
abhishek nair

Reputation: 345

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

Upvotes: 1

victor_destiny
victor_destiny

Reputation: 11

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

Upvotes: 0

Related Questions