通过SSH隧道无需密码MySQL连接字符串(mySQL connection string thro

2019-10-18 14:15发布

我一直在给一台服务器运行MySQL SSH访问。 我的访问是通过我的公钥验证,不需要进一步的密码。

使用腻子,我能够ssh来使用我的私有密钥服务器,直接登录到通过命令行工具的MySQL数据库和直接运行SQL。 我期待通过C#服务(通过SSH连接转发端口3306)来模拟此,不幸的是,在所有列出的连接字符串http://www.connectionstrings.com/mysql/需要密码。

我的粗糙和准备代码到目前为止,使用MySql.DataSSH.NET

  PrivateKeyFile file = new PrivateKeyFile(@" [ path to private key ]");
  using (var client = new SshClient(" [ server ] ", "ubuntu", file))
  {

      var port = new ForwardedPortLocal(3306, "localhost", 3306);
      client.AddForwardedPort (port);
      client.Connect();

      var connection = new MySqlConnection(
           "server=localhost;database=[database];uid=ubuntu;"
      );
      MySqlCommand command = connection.CreateCommand();
      MySqlDataReader Reader;
      command.CommandText = "select * from sample";
      connection.Open();
      Reader = command.ExecuteReader();
      while (Reader.Read())
      {
          string thisrow = "";
          for (int i = 0; i < Reader.FieldCount; i++)
              thisrow += Reader.GetValue(i).ToString() + ",";
          Console.Write(thisrow);
      }
      connection.Close();
      client.Disconnect();
 }

运行代码,而不SshClient部分,在本地网络上跟一个数据库(与已知用户名和密码),是可以正常使用。 随着SshClient中,并用断点部分,一旦隧道已经成立,我可以telnet到localhost:3306 ,并得到响应从MySQL回来。

但是,下面的错误是扔在connection.Open()行:

验证举办的“localhost”用户“Ubuntu的”使用方法“mysql_native_password”有消息失败:拒绝访问用户“Ubuntu的” @“localhost”的(使用密码:YES)

所以......我需要什么连接字符串? 还是我错过了在其他地方一些微妙?

Answer 1:

MySQL是能够拒绝登录,如果他们从错误的主机连接。 也许你并没有让Ubuntu的,以从本地主机连接?

https://dev.mysql.com/doc/refman/5.1/en/connection-access.html



Answer 2:

原来,这个问题是相关的SSH隧道本身; 创建使用腻子,而不是和删除所有该行之前运行的代码隧道:

  var connection = new MySqlConnection(
       "server=localhost;database=[database];uid=ubuntu;"
  );

现在成功了。

两个经验教训:

  • 如果MySQL并不需要一个能允许省略密码。
  • MySQL的错误信息可以做更加明确。


文章来源: mySQL connection string through SSH tunnel without password