Search code examples
pythonmysqldatabasepymysqlssh-tunnel

Accessing a remote database through SSH tunnel


I want to access a remote database through SSH tunnel.

server = SSHTunnelForwarder(
    ('172.17.9.125', 22),
    ssh_password="123456",
    ssh_username="root",
    remote_bind_address=('127.0.0.1', 3306))

server.start()

database = pymysql.connect(host='127.0.0.1',
                           port=3306,
                           user='root',
                           passwd='root')

try:
    dbsql = "CREATE DATABASE TestDB"  # Create database
except Exception as e:
    print("Error: ", e)
database.cursor().execute(dbsql)

global db, cursor
db = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='TestDB')

cursor = db.cursor()
print("Connected to MySQL database")

f = open("testdb.sql")  # Execute .sql file, creating data tables
full_sql = f.read()
sql_commands = full_sql.split(';')[:-1]
try:
    for sql_command in sql_commands:
        if sql_command is not None:
            cursor.execute(sql_command)
        else:
            print("Null")
    print("Created database")
except Exception as e:
    print("Error: ", e)

I want to create a new database named as "TESTDB" on this remote server, 172.17.9.125.

But I get this database created in localhost. What am I doing wrong here?


Solution

  • Since you already have a database running, your 3306 port is used in that so won't be able to bind.

    Solution : bind it to some other port and try to connect to that.

    You can bind to another address using local_bind_address=('0.0.0.0', 1234) (this will be your target local address/port to which it will be bound) in your arguments to SSHTunnelForwarder.

    So your connection TunnelForwarder should be something like this

    server = SSHTunnelForwarder(
        ('172.17.9.125', 22),
        ssh_password="123456",
        ssh_username="root",
        local_bind_address=('0.0.0.0', 1234),
        remote_bind_address=('127.0.0.1', 3306))
    

    And now connection will be made to port 1234

    database = pymysql.connect(host='127.0.0.1',
                               port=1234,
                               user='root',
                               passwd='root')
    
    
    db = pymysql.connect(host='127.0.0.1', port=1234, user='root', passwd='root', db='TestDB')