C# SSH 隧道 Postgres 数据库连接 [英] C# SSH tunnel Postgres database connection

查看:190
本文介绍了C# SSH 隧道 Postgres 数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to connect to the Postgres database on remote server through SSH tunnel. I am using SSH.NET and Npgsql library. Here is my example code:

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: 试图读取流的末尾.

Npgsql.NpgsqlException: 'Exception while reading from stream' EndOfStreamException: Attempted to read past the end of the stream.

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

I am able to connect to database using DBeaver.

推荐答案

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

The remote end of the port forwarding is resolved on the server. So you need set the IP address/hostname in a way that works, as it you are connecting from the server itself.

数据库可能只监听 localhost 接口.不在公共 IP 地址上(如果是,您可能一开始就不需要端口转发).

The database probably listens on the localhost interface only. Not on the public IP address (if it were, you possibly would not need the port forwarding in the first place).

此外,对本地转发端口进行硬编码也不是一个好主意.您无法知道该端口是否已被其他应用程序占用.让系统选择任何空闲的本地端口.

Additionally, it is not a good idea to hard-code the local forwarded port. You cannot know, if that port is not already occupied by another application. Let the system choose any free local port.

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();
}

相关:SSH.NET 中的 MySQL 端口转发 - 尝试以访问权限禁止的方式访问套接字

这篇关于C# SSH 隧道 Postgres 数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆