2015-09-24 61 views
0

我嘗試使用SSH隧道使用C#來訪問我的MySQL數據庫,但我發現了一個異常SSH使用C#

Unable to connect to any of the specified MySQL hosts.

我得到這個代碼與此幫助下隧道MySQL數據庫連接:
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」,而是連接到「本地主機」。

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 = username; password = pass; database = mydatabase; charset = utf8; Allow User Variables = True」; 現在,我得到一個MySQL異常,說錯誤:0:從流中讀取失敗。 –

+0

您的新設置看起來正確。 –