Connect to remote MySQL database using SSH



  • Hello!
    I need your help with Qt database and SSH. I want to establish a connection with remore MySQL database using SSH. For SSH I use libssh and the folloing code:

    Settings settings; const Settings::SSH &ssh{settings.loadSSH()}; ssh_key key;
    int code = ssh_pki_import_privkey_file("key.ossh", ssh.password.toStdString().c_str(), NULL, NULL, &key);
    if(code != SSH_OK)
    {
    	_logger->logOnce("Bad private key!");
    	return false;
    }
    
    ssh_options_set(_ssh, SSH_OPTIONS_HOST, ssh.host.toStdString().c_str());
    code = ssh_connect(_ssh);
    if(code != SSH_OK)
    {
    	_logger->logSshErrorOnce("Unable to connect to host!", _ssh);
    	return false;
    }
    code = ssh_userauth_publickey(_ssh, ssh.login.toStdString().c_str(), key);
    if(code != SSH_AUTH_SUCCESS)
    {
    	_logger->logSshErrorOnce("Unable to authorize!", _ssh);
    	return false;
    }
    code = ssh_channel_open_forward(_channel, ssh.host.toStdString().c_str(), 22, "localhost", 3307);
    if(code != SSH_OK)
    {
    	_logger->logSshErrorOnce("Unable to create ssh-channel!", _ssh);
    	return false;
    }
    

    It works and there are no errors. BUT, what I should do next to transfer data from my Qt database to ssh tunnel? May be I need to use something in addition (classes, libs...)?
    If I write after the code above this:

    const Settings::Database &db{settings.loadDatabase()};
    _db = QSqlDatabase::addDatabase("QMYSQL", "my_database");
    _db.setPort(3307);
    _db.setHostName("localhost");
    _db.setDatabaseName("test_db");
    _db.setUserName(db.login);
    _db.setPassword(db.password);
    
    _db.open();
    

    then Qt says that there is a connection error...
    How to correctly make the connection? Help please.

    PS I dont want to use QProcess and run external tunneler like plink.exe.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You can find here how to setup an ssl connection from your server.

    Hope it helps



  • Hello!
    I asked about SSH connection not SSL. SSH != SSL, yes?


  • Lifetime Qt Champion

    Indeed, I've mixed both.

    Do you have more details about the exact error that was reported ?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.