C# SSH 隧道 Postgres 数据库连接

标签 c# ssh npgsql ssh-tunnel ssh.net

我正在尝试通过 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: 'Exception while reading from stream' EndOfStreamException: Attempted to read past the end of the stream.

我可以使用 DBeaver 连接到数据库。

最佳答案

端口转发的远端在服务器上解析。因此,您需要以有效的方式设置 IP 地址/主机名,因为它是从服务器本身 连接的。

数据库可能只监听 localhost 接口(interface)。不在公共(public) 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();
}

相关:MySQL port forwading in SSH.NET - An attempt was made to access a socket in a way forbidden by its access permissions

关于C# SSH 隧道 Postgres 数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58207371/

相关文章:

linux - 在ubuntu中以root身份远程登录

c# - 如何在 C# 和 Npgsql 中使用不带双引号的 PostgreSQL 表名

c# - MySQL查询超时

c# - INotifyPropertyChanged PropertyChangedEventHandler 事件始终为 null

ssh - Shell脚本可使用密码自动进行SSH登录

.net - 当从 .NET 中访问 PostgreSQL 时,是否存在阻止 Npgsql 提供多个并发读取器的内在限制?

.net - 具有多个语句的 Npgsql 命令

c# - 如何强制 Entity Framework 映射 `internal` 导航属性?

c# - 有没有办法将任意数据关联到 Windows 进程?

windows - SSH Windows 到 UNIX