Search code examples
linuxpostgresqlasp.net-corescaffolding

How to do a scaffold over a ssh tunnel


I have a postgres database on a remote computer that I need to use

To log on to that computer I do the usual,

ssh <myuser>@<subdomain.domain.com> -p <custom port>

Once logged in, I must again

ssh <someServerName>

Then I can do

psql -U postgres -W

and get into the database

So in short, I need to do ssh something twice

Is it possible to connect to this database using entity framework core?

Bonus question: Would this be called a ssh tunnel?

Solution

It´s called Port Fowarding

using (var client = new SshClient("<public ip>", <port>, "<myuser>", "<mypassword>"))
{
    client.Connect();

    var port = new ForwardedPortLocal("localhost", 5432, "10.0.0.5", 5432);
    client.AddForwardedPort(port);

    port.Start();

    using (var conn = new NpgsqlConnection("Server=localhost;Database=<secret>;Port=5432;User Id=postgres;Password=<secret>;"))
    {
        conn.Open();
    }

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

Solution

  • Assuming you want to run psql command from your local host, you can do :

    ssh -t <myuser>@<subdomain.domain.com> -p <custom port> ssh -t <someServerName> psql -U postgres -W
    

    To do the port forwarding (SSH tunneling), you can do in one terminal :

    ssh -L 5432:someServerName:5432 <myuser>@<subdomain.domain.com> -p <custom port>
    

    -L 5432:someServerName:5432 means now the port 5432 on localhost is forwarded to someServerName:5432 (port used by postgres)