Monday, January 29, 2024

[SOLVED] sshtunnel is not using specified key and not using private key password

Issue

I'm writing a script that needs to connect to a MySQL server via SSH. I have the following:

import mysql.connector
from sshtunnel import SSHTunnelForwarder


def query_mysql_server(query):
    with SSHTunnelForwarder(
        ('ssh_server_ip', 22),
        ssh_username='sshuser',
        ssh_pkey='/Users/myhomedir/.ssh/id_rsa',
        ssh_private_key_password='my_ssh_key_passphrase',
        remote_bind_address=('127.0.0.1', 3306)
    ) as server:

        conn = mysql.connector.connect(
            host='127.0.0.1',
            port=server.local_bind_port,
            user='mysqluser',
            password='mysqluserpass',
            database='mydb'
        )

        cursor = conn.cursor()
        cursor.execute(query)

        results = cursor.fetchall()
        for row in results:
            print(row)

        cursor.close()
        conn.close()

query = "SELECT * FROM users;"
query_mysql_server(query)

Running this results in the error ERROR | Password is required for key /Users/myhomedir/.ssh/id_rsa. I've also tried using a different key (/Users/myhomedir/.ssh/app_key), that doesn't have a pass phrase set at all and get exactly the same error, referring to the "default" key id_rsa, so an alternative key is not picked up for some reason.

Both keys are added to the ssh authentication agent using ssh-add. The default key (id_rsa) is an RSA key, not an OpenSSH key.

System is macOS.

Any help is appreciated!


Solution

After troubleshooting it further and trying invalid SSH credentials I realized that the SSH tunnel actually works and the code hung on mysql.connector.connect until I added use_pure=True. Seemingly this error shows up always, regardless if the connection succeeds or not. The ssh_pkey also works as intended and will use the specified key file, but will still raise the error in question quoting the "default" key id_rsa.

Same issue is described here: SSHTunnel searching for default private key (id_rsa) instead of the ssh_pkey I specify



Answered By - equinoxe5
Answer Checked By - Robin (WPSolving Admin)