Monday, September 19, 2011

Connecting MySql over SSH using C#

I am sure many of you are looking for C# code to connect to MySql server over SSH.
I hope you are aware of SSH , if not please google SSH and know more about the SSH in details.


.Net does not have its own inbuilt methods or classes for connecting to MySql over SSH.
Hence you will need to download few open source dlls for the implementing your code to connect to MqSql over SSH.


I am going to use sharpSSH here. Thanks to Tamir for writing the code and sharing with the world.
You can download the library from here. Also you will need the secret key file in openSSH format to connect. You can get the key in openSSH format generated from puttygen.


Here is the code for MySql Connection over SSH using C#

using System;

using System.Collections;
using MySql.Data.MySqlClient;
using Tamir.SharpSsh.jsch;


namespace MySQLSSHConnection
{
class Program
{
static void Main(string[] args)
{
 MySqlConnection myConnection = null;
 Session sshSession = null;
 try
 {
  JSch jsch = new JSch();
                
  //Setting the secret key file
  jsch.addIdentity(@"D:\...\key-file");
  sshSession = jsch.getSession("username", hostname, 22);
                                
  Hashtable config = new Hashtable();
  config.Add("StrictHostKeyChecking", "No");            
  sshSession.setConfig(config);


  //Setting the SSH connection
  sshSession.connect();
                
  //Forwarding the remote port to local port over the connected session
  sshSession.setPortForwardingL(3306, "localhost", 3306);


  //Connecting to Mysql 
  string connstring = "Server=localhost;Port=3306;database=Account;Uid=****;Password=****";
  myConnection = new MySqlConnection(connstring);
  myConnection.Open();                
  Console.WriteLine("Open OK");
  Console.ReadLine();                
 }
 catch(Exception ex)
 {
   Console.WriteLine(ex.ToString());
   Console.ReadLine();
 }
 finally
 {
  //Closing database connection
  myConnection.Close();


  //Closing SSH connection
  sshSession.disconnect();
 }
}
}
}


Hope this post is helpful.