MySQL Connector/NET Developer Guide

4.2.2 SSH Connection Examples for Classic MySQL Protocol

The examples in this section demonstrate how to make classic MySQL protocol connections using standard TCP/IP over SSH:

Basic SSH Connection with Defaults

This example shows the most basic form of the SSH tunnel connection. The MySQL port defaults to 3306 and the SSH port defaults to 22, because the values are not configured. Also, only a password is provided to authenticate to the SSH server. In this example, the connection is made using a MySqlConnectionStringBuilder object.

var builder = new MySqlConnectionStringBuilder();
builder.UserID = "myUser";
builder.Password = "test";
builder.Server = "localhost";
builder.SshHostName = "10.0.0.2";
builder.SshUserName = "mySshUser";
builder.SshPassword = "sshtest";
using (var connection = new MySqlConnection(builder.ConnectionString))
{
  connection.Open();
  connection.Close();
}  

SSH Connection With Ports

In this SSH tunneling example, the MySQL and SSH ports are configured to override the default values. Only a password is provided to authenticate to the SSH server. Note that the connection is made using a connection string.

using (var connection = new MySqlConnection("uid=myUser;password=test;server=localhost;port=3307;
          sshHostName=10.0.0.2;sshUserName=mySshUser;sshPassword=sshtest;sshPort=23"))
{
  connection.Open();
  connection.Close();
}    

SSH Connection With Key File

In addition to making the connection with a password, this example also includes a key file and pass phrase. Like the previous example, both the MySQL and SSH ports are configured.

using (var connection = new MySqlConnection("uid=myUser;password=test;server=localhost;port=3307;
          sshHostName=10.0.0.2;sshUserName=mySshUser;sshKeyFile=C:\\keys\\myOpenSshKeyFile.ppk;
          sshPassPhrase=sshTest;sshPort=23"))
{
  connection.Open();
  connection.Close();
}      

SSH Connection with Fallback

This example includes the SSH key file (without a pass phrase) and the SSH password. Because the key file is valid and the pass phrase is not required, the connection can fall back to the SSH password value if authentication with the SSH key file encounters an error on the server.

var builder = new MySqlConnectionStringBuilder();
builder.UserID = "myUser";
builder.Password = "test";
builder.Server = "localhost";
builder.Port = 3307;
builder.SshHostName = "10.0.0.2";
builder.SshUserName = "mySshUser";
builder.SshKeyFile = @"C:\keys\noPassPhraseOpenSshKeyFile.ppk";
builder.SshPassword = "sshtest";
using (var connection = new MySqlConnection(builder.ConnectionString))
{
  connection.Open();
  connection.Close();
}