Pergunta

I'm trying to connect to a remote mysql server using a SSH tunnel set up using OpenSSH key file and SSH.Net library as shown in the code section below...

try
{
    PrivateKeyFile pkfile = new PrivateKeyFile("C:\\Users\\OpenSSHKey", "mypassword");
    var client = new SshClient("servername.com", 22, "myusername", pkfile);
    client.Connect();
    if (client.IsConnected)
    {
        var local = new ForwardedPortLocal(22, "localhost", 3306);
        client.AddForwardedPort(local);
        try
        {
            local.Start();
        }
        catch (SocketException se)
        {

        }
        string connStr = "server=localhost;user=mysql_username;database=database_name;port=3306;password=MyDBPassword;";
        MySqlConnection sql = new MySqlConnection(connStr);
        sql.Ping();
        try
        {
            sql.Open();
        }
        catch (MySqlException se)
        {
        }
    }
}
catch(Exception e)
{
}

the tunnel is definitely set up because it throws the following error "Unable to connect to any of the specified MySQL hosts" on the sql.Open() call...

Im sure the database is on the server named mysername because I can connect to it using putty or workbench with the credentials used in the MYSQL connection string... I hope someone can help

Foi útil?

Solução

I've just solved exactly this problem myself. Simply change your ForwardedPortLocal to:

    var local = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 3306);

In your original, you were giving the source port as 22. However, your MySql connection would have been connecting to port 3306 on your local machine (which you would then tunnel across to port 3306 on the destination), so you need to ensure that the forwarded port is listening locally on 3306 to start with.

In addition, I've changed localhost to 127.0.0.1. A secondary issue I tripped over was that localhost on my machine was actually resolving to ::1, an IPv6 address, and the destination server didn't 'speak' IPv6. By switching this to the 127.0.0.1 (IPv4's version of localhost), it ensures that IPv4 is used by default.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top