【发布时间】:2020-01-21 01:40:23
【问题描述】:
我正在尝试为使用 SSH 隧道从远程 PostgreSQL 服务器更新本地数据库的程序自动创建 SSH 连接。到目前为止,我一直在使用 PuTTY 手动打开隧道(包括使用 -L 命令的本地端口转发指令)。我想在程序运行时使用 ssh.net 自动打开端口。建立连接后,程序使用 Entity Framework Core 访问远程数据库。
当我用 PuTTY 打开 SSH 连接时,程序运行良好。这是 PuTTY 命令:
//plink.exe -i "C:\Users\user.name\Desktop\host_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。
当 Entity Framework Core 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 和端口转发对我来说是新的,请告诉我我在哪里是个白痴。
【问题讨论】:
-
你在PostgreSQL服务器的
postgresql.conf文件中设置ssl = on并重启了吗? -
你从哪里得到
ExtendedSocketException? + 向我们展示完整的异常调用堆栈。 +Dns.GetHostAddresses(string.Empty)返回什么? -
Program.RunBackup();中的代码是不是和你通过putty隧道连接成功的一样?
标签: c# postgresql entity-framework-core portforwarding ssh.net