C#SSH隧道Postgres数据库连接

问题描述 投票:1回答:1

我正在尝试通过SSH隧道连接到远程服务器上的Postgres数据库。我正在使用SSH.NET和Npgsql库。这是我的示例代码:

using (var client = new SshClient("210.130.90.110", "root", "pasword"))
{
    client.Connect();

    if (!client.IsConnected)
    {
        // Display error
        Console.WriteLine("Client not connected!");
    }
    else
    {
        Console.WriteLine("Client connected!");
    }

    var port = new ForwardedPortLocal("127.0.0.1", 15432, "210.130.90.110", 5432);
    client.AddForwardedPort(port);

    port.Start();

    using (var conn = new NpgsqlConnection("Server=127.0.0.1;Database=dbname;Port=15432;User Id=dbuser;Password=dbpassword;"))
    {
        conn.Open();
    }

    port.Stop();
    client.Disconnect();
}

执行代码后,我得到:

Npgsql.NpgsqlException:'从流中读取时发生异常'EndOfStreamException:尝试读取流的末尾。

我能够使用DBeaver连接到数据库。

c# ssh npgsql ssh-tunnel ssh.net
1个回答
0
投票

端口转发的远端在服务器上已解决。因此,您需要以一种可行的方式设置IP地址/主机名,因为您正在连接来自服务器本身

数据库可能仅在localhost接口上侦听。不在公共IP地址上(如果有的话,一开始您可能不需要端口转发)。

此外,对本地转发的端口进行硬编码不是一个好主意。您不知道该端口是否尚未被另一个应用程序占用。让系统选择任何可用的本地端口。

var port = new ForwardedPortLocal("127.0.0.1", "127.0.0.1", 5432);
client.AddForwardedPort(port);
port.Start();

string connString =
    $"Server={port.BoundHost};Database=dbname;Port={port.BoundPort};" +
     "User Id=dbuser;Password=dbpassword;";

using (var conn = new NpgsqlConnection(connString))
{
    conn.Open();
}
© www.soinside.com 2019 - 2024. All rights reserved.