mysql连接字符串 端口,通过SSH隧道的mySQL连接字符串,无需密码

I've been given SSH access to a server running mySQL. My access is authenticated through my public key, with no further password required.

Using Putty, I am able to SSH to the server using my private key, log directly into the mySQL database via the command-line tools and run SQL directly. I'm looking to emulate this through a C# service (forwarding port 3306 through the SSH connection), unfortunately all the connection strings listed at http://www.connectionstrings.com/mysql/ require a password.

My rough-and-ready code so far, using MySql.Data and 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();

}

Running the code without the SshClient section, talking to a database on the local network (with a known username and password), is working perfectly. With the SshClient section in, and with a breakpoint once the tunnel has been set up, I can telnet to localhost:3306 and get a response back from mySQL.

However, the following error is thrown on the connection.Open() line:

Authentication to host 'localhost' for user 'ubuntu' using method 'mysql_native_password' failed with message: Access denied for user 'ubuntu'@'localhost' (using password: YES)

So ... what connection string do I need? Or have I missed something subtle elsewhere?

解决方案

The problem turned out to be related to the SSH tunnel itself; creating the tunnel using Putty instead and removing all the code that runs before the line:

var connection = new MySqlConnection(

"server=localhost;database=[database];uid=ubuntu;"

);

now succeeds.

Two lessons learnt:

It is allowable to omit the password if mySQL does not require one.

mySQL's error messages could do with being more explicit.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值