首页 > 解决方案 > 无法使用 c# 连接 AWS (EC2) 数据库 (mysql) SSH 隧道

问题描述

我无法使用 SSH 隧道 (C#) 连接到 AWS。
我总是收到此错误:
异常抛出:Renci.SshNet.dll 中
的“System.Net.Sockets.SocketException”在数据库查找期间发生不可恢复的错误

我可以使用 Workbench 进行连接

我正在使用与此相同的代码

而且我正在尝试使用此代码:感谢所有者:
当我到达此代码时client.Connect(); ,与上述相同的错误。

string SshHostName = "ec2-****@***-**-***-***-***.**-northeast-1.compute.amazonaws.com";
string SshUserName = "ec2-****";
string SshKeyFile = @"C:\Users\develop\.ssh\testing.pem";

string Server = "127.0.0.1";
int Port = 3306;
string UserID = "UserID";
string Password = "password";
string DataBase = "database_name";

ConnectionInfo cnnInfo;

using (var stream = new FileStream(SshKeyFile, FileMode.Open, FileAccess.Read))
{
  var file = new PrivateKeyFile(stream);
  var authMethod = new PrivateKeyAuthenticationMethod(SshUserName, file);
  cnnInfo = new ConnectionInfo(SshHostName, 22, SshUserName, authMethod);
}

using (var client = new SshClient(cnnInfo))
{
   client.Connect();
     if (client.IsConnected)
     {
       var forwardedPort = new ForwardedPortLocal("127.0.0.1", Server, Port);
       client.AddForwardedPort(forwardedPort);
       forwardedPort.Start();

       string connStr = $"Server = {forwardedPort.BoundHost};Port = {forwardedPort.BoundPort};Database = {DataBase};Uid = {UserID};Pwd = {Password};";

       using (MySqlConnection cnn = new MySqlConnection(connStr))
        {
          cnn.Open();

           MySqlCommand cmd = new MySqlCommand("SELECT * FROM PostalCodes LIMIT 25;", cnn);
           MySqlDataReader reader = cmd.ExecuteReader();

           while (reader.Read())
               Console.WriteLine($"{reader.GetString(1)}, {reader.GetString(2)}, {reader.GetString(3)}");

                    Console.WriteLine("Ok");

                    cnn.Close();
                }

                client.Disconnect();
            }

        }

标签: c#amazon-web-services

解决方案


推荐阅读