2015-09-24 3 views
0

Я пытался использовать SSH туннелирование для доступа к моей базе данных MySQL, используя C#, но я получаю исключениеSSH туннелирование соединения MySQL, используя C#

Unable to connect to any of the specified MySQL hosts.

Я получил этот код с помощью этого:
C# SSH tunnel to MySQL server

Вот мой код:

PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo("example.com", 2222, "username", "password"); 
connectionInfo.Timeout = TimeSpan.FromSeconds(30); 

using (var client = new SshClient(connectionInfo)) 
{ 
    try 
    { 
     Console.WriteLine("Trying SSH connection..."); 
     client.Connect(); 
     if (client.IsConnected) 
     { 
      Console.WriteLine("SSH connection is active: {0}", client.ConnectionInfo.ToString()); 
     } 
     else 
     { 
      Console.WriteLine("SSH connection has failed: {0}", client.ConnectionInfo.ToString()); 
     } 

     Console.WriteLine("\r\nTrying port forwarding..."); 
     var portFwld = new ForwardedPortLocal(IPAddress.Loopback.ToString(),2222, "example.com", 3306); 
     client.AddForwardedPort(portFwld); 
     portFwld.Start(); 
     if (portFwld.IsStarted) 
     { 
      Console.WriteLine("Port forwarded: {0}", portFwld.ToString()); 
    Console.WriteLine("\r\nTrying database connection..."); 

DBConnect dbConnect = new DBConnect("127.0.0.1", "database", "username", "password", "3306"); 
    int id = dbConnect.Count("table"); 
    MessageBox.Show(id + " count "); 
      } 
      else 
      { 
       Console.WriteLine("Port forwarding has failed."); 
      } 

     } 
     catch (SshException ex) 
     { 
      Console.WriteLine("SSH client connection error: {0}", ex.Message); 
     } 
     catch (System.Net.Sockets.SocketException ex1) 
    { 
     Console.WriteLine("Socket connection error: {0}", ex1.Message); 
    } 

} 
private MySqlConnection connection; 

private string server; 
public string Server 
{ 
    get 
    { 
     return this.server; 
    } 
    set 
    { 
     this.server = value; 
    } 
} 

private string database; 
public string Database 
{ 
    get 
    { 
     return this.database; 
    } 
    set 
    { 
     this.database = value; 
    } 
} 

private string uid; 
public string Uid 
{ 
    get 
    { 
     return this.server; 
    } 
    set 
    { 
     this.server = value; 
    } 
} 

private string password; 
public string Password 
{ 
    get 
    { 
     return this.password; 
    } 
    set 
    { 
     this.password = value; 
    } 
} 

private string port; 
public string Port 
{ 
    get 
    { 
     return this.port; 
    } 
    set 
    { 
     this.port = value; 
    } 
} 

//Constructor 
public DBConnect(string server, string database, string uid, string password, string port = "3306") 
{ 
    this.server = server; 

    this.database = database; 
    this.uid = uid; 
    this.password = password; 
    this.port = port; 

    Initialize(); 
} 

//Initialize values 
private void Initialize() 
{ 
    string connectionString; 
    connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";"; 
    connection = new MySqlConnection(connectionString); 
} 


//open connection to database 
private bool OpenConnection() 
{ 
    try 
    { 
     connection.Open(); 
     Console.WriteLine("MySQL connected."); 
     return true; 
    } 
    catch (MySqlException ex) 
    { 
     //When handling errors, you can your application's response based on the error number. 
     //The two most common error numbers when connecting are as follows: 
     //0: Cannot connect to server. 
     //1045: Invalid user name and/or password. 
     switch (ex.Number) 
     { 
      case 0: 
       Console.WriteLine("Cannot connect to server. Contact administrator"); 
       break; 

      case 1045: 
       Console.WriteLine("Invalid username/password, please try again"); 
       break; 

      default: 
       Console.WriteLine("Unhandled exception: {0}.", ex.Message); 
       break; 

     } 
     return false; 
    } 
} 

//Close connection 
private bool CloseConnection() 
{ 
    try 
    { 
     connection.Close(); 
     return true; 
    } 
    catch (MySqlException ex) 
    { 
     Console.WriteLine(ex.Message); 
     return false; 
    } 
} 

//Count statement 
public int Count(string tableName) 
{ 
    string query = "SELECT Count(*) FROM " + tableName; 
    int Count = -1; 

    //Open Connection 
    if (this.OpenConnection() == true) 
    { 
     //Create Mysql Command 
     MySqlCommand cmd = new MySqlCommand(query, connection); 

     //ExecuteScalar will return one value 
     Count = int.Parse(cmd.ExecuteScalar() + ""); 

     //close Connection 
     this.CloseConnection(); 

     return Count; 
    } 

    return Count; 

} 

Вывод, который я получил в моей консоли:

Trying SSH connection... 
A first chance exception of type 'System.ObjectDisposedException' occurred in mscorlib.dll 
A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll 
SSH connection is active: Renci.SshNet.PasswordConnectionInfo 

Trying port forwarding... 
Port forwarded: Renci.SshNet.ForwardedPortLocal 
A first chance exception of type 'Renci.SshNet.Common.SshConnectionException' occurred in Renci.SshNet.dll 

Trying database connection... 
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll 
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in MySql.Data.dll 
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll 
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll 
Error: 0 : Unable to connect to any of the specified MySQL hosts. 
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll 
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll 
Unhandled exception: Unable to connect to any of the specified MySQL hosts.. 

UPATE:

Я изменил настройки переадресации порта:

var portFwld = new ForwardedPortLocal("127.0.0.1", 1000, "127.0.0.1", 3306); 

и я изменил мой MySql Строка к:

connectionString = "server=127.0.0.1;port=1000; UID=username; password=password; database=data1; charset=utf8;Allow User Variables=True"; 

Я подключен к SSH и мой порт пересылается, но я до сих пор не могу подключиться к базе данных MySQL, я получаю исключение:

A first chance exception of type 'System.IO.EndOfStreamException' occurred in MySql.Data.dll 
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll 
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll 
Error: 0 : Reading from the stream has failed. 

ответ

1

Вы должны подключить MySQL к связанному порту пересылки. То есть к 2222.

Или еще более семантически правильно, используйте portFwld.BoundPort. Эквивалентно, используйте portFwld.BoundHost.

DBConnect dbConnect = new DBConnect(portFwld.BoundHost, "database", "username", "password", portFwld.BoundPort); 

отметить также, что это имеет смысл обратиться к хосту MySQL, как «локальный», а не «example.com», так как имя хоста решается на стороне сервера. И когда на стороне сервера вы обычно не подключаетесь к «example.com», а к «localhost».

var portFwld = new ForwardedPortLocal(IPAddress.Loopback.ToString(), 2222, "localhost", 3306); 

И, конечно, нужно держать SSH сессию открытой, пока вам нужен туннель. Таким образом, вы должны подключиться к БД в пределах using блока:

using (var client = new SshClient(connectionInfo)) 
{ 
    ... 
    client.Connect(); 
    ... 
    portFwld.Start(); 
    ... 
    DBConnect dbConnect = new DBConnect(portFwld.BoundHost, "database", "username", "password", portFwld.BoundPort); 
} 
+0

порт перенаправляется, но база данных не подключиться –

+0

Это не сработало, я получаю ту же ошибку, поэтому я вручную настроить и я изменил порт вперед на: var portFwld = new ForwardedPortLocal (IPAddress.Loopback.ToString(), 2222, «localhost», 3306); и я изменил строку подключения на это: connectionString = "server = localhost; port = 2222; UID = имя пользователя; пароль = pass; database = mydatabase; charset = utf8; Разрешить пользовательские переменные = True"; Теперь я получаю исключение MySQL, говорящее об ошибке: 0: Чтение из потока не удалось. –

+0

Ваша новая настройка выглядит правильно. –