Haga un túnel SSH a otra computadora a través de R para acceder a la tabla postgreSQL

Como parte de mi flujo de trabajo R para uno de mis proyectos, cargo datos de una tabla postgreSQL ubicada en un servidor remoto.

Mi código se ve así (credenciales anónimas).

Primero abro una conexión ssh al servidor remotoen terminal.

ssh -p Port -L LocalPort:IP:RemotePort servername"

Luego me conecto a la base de datos postgres en R.

# Load the RPostgreSQL package
library("RPostgreSQL")

# Create a connection
Driver <- dbDriver("PostgreSQL") # Establish database driver
Connection <- dbConnect(Driver, dbname = "DBName", host = "localhost", port = LocalPort, user = "User")

# Download the data
Data<-dbGetQuery(Connection,"SELECT * FROM remote_postgres_table")

Este enfoque funciona bien y puedo descargar los datos sin problemas.

Sin embargo, me gustaría hacer el primer paso, es decir, crear la conexión ssh, en R, en lugar de en la terminal. Aquí está mi intento de hacerlo, con el correspondiente error.

# Open the ssh connection in R
system("ssh -T -p Port -L LocalPort:IP:RemotePort servername")

# Load the RPostgreSQL package
library("RPostgreSQL")

# Create a connection
Driver <- dbDriver("PostgreSQL") # Establish database driver
Connection <- dbConnect(Driver, dbname = "DBName", host = "localhost", port = LocalPort, user = "User")

# Download the data
Data<-dbGetQuery(Connection,"SELECT * FROM remote_postgres_table")

Error in postgresqlExecStatement(conn, statement, ...) : 
RS-DBI driver: (could not Retrieve the result : server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.

Para aclarar mi pregunta, me gustaría realizar todo este flujo de trabajo (establecer una conexión, descargar datos postgreSQL) completamente en R sin ningún paso en la terminal.

Respuestas a la pregunta(2)

Su respuesta a la pregunta