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.