无法通过 SSH 连接到 PostgreSQL 服务器:无法建立连接,因为目标计算机主动拒绝了它



我正在尝试为使用SSH隧道从远程PostgreSQL服务器更新本地数据库的程序自动创建SSH连接。到目前为止,我一直在使用 PuTTY 手动打开隧道(包括使用 -L 命令的本地端口转发指令(。我想使用 ssh.net 在程序运行时自动打开端口。建立连接后,程序将使用实体框架核心访问远程数据库。

当我打开与PuTTY的SSH连接时,程序运行良好。这是 PuTTY 命令:

//plink.exe -i "C:Usersuser.nameDesktophost_private_key.ppk" -L 6544:111.22.33.66:6543 -N user@address.io -pw *PASSWORD*"

(为了保护隐私,删除了登录详细信息(

这是我尝试打开同一连接 ssh.net 代码:

public void MakeSSHTunnel()
{
string password = "password";
// path of RSA private key in openSSH format:
string privateKeyPath = "C:/Users/user.name/.ssh/id_rsa";
try
{
// creates variable to transmit RSA private key + passphrase to server via SSH.NET, openSSH compatible.
var privateKeyFile = new PrivateKeyFile(privateKeyPath, password);
string serverAddress = "address.io";
string user = "user";
// allows for the remote port forwarding options required by the server 
using (var client = new SshClient(serverAddress, user, privateKeyFile))
{
client.Connect();
var tunnel = new ForwardedPortLocal(6544, "111.22.33.66", 6543);
client.AddForwardedPort(tunnel);
// testing weather the connection has been successful:
if (client.IsConnected)
{
Console.WriteLine("OPENTUNNEL.CS: Connection to {0} successful.", serverAddress);
state = "Open";
}
else
{
Console.WriteLine("Connection to {0} failed.");
state = "Closed";
}
tunnel.Exception += delegate (object sender, ExceptionEventArgs e)
{
Console.WriteLine(e.Exception.ToString());
};
tunnel.Start();
Program.RunBackup();

// ... closes the port ... //
tunnel.Stop();
client.Disconnect();
}
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e);
}
}

我很困惑,因为在上面,if (client.IsConnected)返回 true。

当实体框架核心 OnConfiguring(( 方法将连接的详细信息与其 optionsBuilder 传递时,似乎发生了错误:

optionsBuilder.UseNpgsql($"Host=127.0.0.1;Port=6544;Database=user;Username=user;Password=databasePassworh;CommandTimeout=300;Timeout=300;SSL Mode=Require;Trust Server Certificate=true;Convert Infinity DateTime=true");

出现的错误是:

NpgsqlException: Exception while connecting

和:

ExtendedSocketException: No connection could be made because the target machine actively refused it. 127.0.0.1:6544

我已经仔细检查了所有密码,并通读了所有 SSH.NET 文档和代码示例,并保留了所有以前工作(通过 PuTTY(的代码。

如果有人能看到我做错了什么,我将不胜感激。C#,SSH.NET 和端口转发对我来说是新的,请告诉我我在哪里是个白痴。

这段代码现在可以工作了。我相信问题在于:

var tunnel = new ForwardedPortLocal(6544, "111.22.33.66", 6543);

"绑定端口"不包含地址。我见过没有定义的例子,并遵循了这些例子。在单步执行代码时,我注意到该字段为空,并决定尝试 127.0.0.1。现在已成功连接到数据库。它适用于:

var tunnel = new ForwardedPortLocal("127.0.0.1", 6544, "111.22.33.66", 6543); 

感谢您对此进行调查并感谢您的贡献。

相关内容

最新更新