通过SSH隧道的mySQL连接字符串,无需密码
本文关键字:密码 字符串 连接 SSH 隧道 mySQL 通过 | 更新日期: 2023-09-27 18:29:20
我已经获得了对运行mySQL的服务器的SSH访问权限。我的访问是通过我的公钥进行身份验证的,不需要进一步的密码。
使用Putty,我可以使用私钥SSH到服务器,通过命令行工具直接登录到mySQL数据库并直接运行SQL。我希望通过C#服务(通过SSH连接转发端口3306)来模拟这一点,不幸的是http://www.connectionstrings.com/mysql/需要密码。
到目前为止,我使用MySql.Data
和SSH.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()
行出现以下错误:
使用方法"mysql_native_password"对用户"ubuntu"的主机"localhost"进行身份验证失败,并显示消息:用户"ubutu"@"localhost"的访问被拒绝(使用密码:YES)
所以。。。我需要什么连接字符串?或者我在其他地方错过了一些微妙的东西?
MySQL能够在从错误的主机连接时拒绝登录。也许您不允许ubuntu从localhost连接?
https://dev.mysql.com/doc/refman/5.1/en/connection-access.html
问题原来与SSH隧道本身有关;使用Putty创建隧道,并删除行之前运行的所有代码:
var connection = new MySqlConnection(
"server=localhost;database=[database];uid=ubuntu;"
);
现在成功了。
吸取的两个教训:
- 如果mySQL不需要密码,则可以省略密码
- mySQL的错误消息可能需要更加明确