我正在尝试创建链接到 MySQL 数据库的服务。我遇到的问题是 MySQL 需要 SSH 密钥,但使用 MySQL 的连接服务没有提供输入 SSH 详细信息的选项。通常在代码中,我会提供 localhost 以及 SSH 文件/密钥。
如何将 SSH 详细信息添加到连接中? 我需要 MySql DB 的链接服务,MySql 配置为使用 SSH。按如下方式设置链接服务并按“测试连接”,我收到超时消息,并且仅假设这是因为我尚未通过 SSH 密钥。
如果我正在编写 Azure 函数,我会通过以下方式连接:
var server = "server ip for MySQL";
var sshUserName = "sshusernameHere";
var sshPassword = "sshpasswordhere";
var databaseUserName = "mysqldatabaseuser";
var databasePassword = "mysqldatabasepassword";
var (sshClient, localPort) = ConnectSsh(server, sshUserName, sshPassword, "path to my ssh key file");
using (sshClient)
{
MySqlConnectionStringBuilder csb = new MySqlConnectionStringBuilder
{
Server = "127.0.0.1",
Port = localPort,
UserID = databaseUserName,
Password = databasePassword,
Database = "databasename"
};
其中
ConnectSsh
是:
public static (SshClient SshClient, uint Port) ConnectSsh(string sshHostName, string sshUserName, string sshPassword = null,
string sshKeyFile = null, string sshPassPhrase = null, int sshPort = 22, string databaseServer = "localhost", int databasePort = 3306)
{
// check arguments
if (string.IsNullOrEmpty(sshHostName))
throw new ArgumentException($"{nameof(sshHostName)} must be specified.", nameof(sshHostName));
if (string.IsNullOrEmpty(sshHostName))
throw new ArgumentException($"{nameof(sshUserName)} must be specified.", nameof(sshUserName));
if (string.IsNullOrEmpty(sshPassword) && string.IsNullOrEmpty(sshKeyFile))
throw new ArgumentException($"One of {nameof(sshPassword)} and {nameof(sshKeyFile)} must be specified.");
if (string.IsNullOrEmpty(databaseServer))
throw new ArgumentException($"{nameof(databaseServer)} must be specified.", nameof(databaseServer));
// define the authentication methods to use (in order)
var authenticationMethods = new List<AuthenticationMethod>();
if (!string.IsNullOrEmpty(sshKeyFile))
{
authenticationMethods.Add(new PrivateKeyAuthenticationMethod(sshUserName,
new PrivateKeyFile(sshKeyFile, string.IsNullOrEmpty(sshPassPhrase) ? null : sshPassPhrase)));
}
if (!string.IsNullOrEmpty(sshPassword))
{
authenticationMethods.Add(new PasswordAuthenticationMethod(sshUserName, sshPassword));
}
// connect to the SSH server
var sshClient = new SshClient(new ConnectionInfo(sshHostName, sshPort, sshUserName, authenticationMethods.ToArray()));
sshClient.Connect();
// forward a local port to the database server and port, using the SSH server
var forwardedPort = new ForwardedPortLocal("127.0.0.1", databaseServer, (uint)databasePort);
sshClient.AddForwardedPort(forwardedPort);
forwardedPort.Start();
return (sshClient, forwardedPort.BoundPort);
}