通过R建立到另一台计算机的SSH隧道以访问postgreSQL表

And*_*ndy 11 ssh r

作为我的一个项目的R工作流程的一部分,我从位于远程服务器上的postgreSQL表中加载数据.

我的代码看起来像这样(匿名凭证).

我首先打开一个到终端远程服务器的ssh连接.

ssh -p Port -L LocalPort:IP:RemotePort servername"
Run Code Online (Sandbox Code Playgroud)

然后我连接到R中的postgres数据库.

# 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")
Run Code Online (Sandbox Code Playgroud)

这种方法工作正常,我可以毫无问题地下载数据.

但是,我想在R中而不是在终端中执行第一步 - 即创建ssh连接.这是我尝试这样做的,伴随着错误.

# 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.
Run Code Online (Sandbox Code Playgroud)

为了澄清我的问题,我想完全在R中执行整个工作流程(建立连接,下载postgreSQL数据),而无需在终端中执行任何步骤.

And*_*ndy 4

根据 @r2evans 的建议。

##### Starting the Connection #####
# Start the ssh connection to server "otherhost"
system2("ssh", c("-L8080:localhost:80", "-N", "-T", "otherhost"), wait=FALSE)
Run Code Online (Sandbox Code Playgroud)

您可以通过手动查找并输入 pid 来终止该进程,也可以通过终止与您的服务器名称匹配的所有 pid 来自动终止该进程。请注意,只有在使用相对唯一且不太可能在其他进程中重复的服务器名称时,才需要使用后一个版本。

##### Killing the Connection: Manually #####
# To end the connection, find the pid of the process
system2("ps",c("ax | grep otherhost"))
# Kill pid (x) identified by the previous grep.
tools::pskill(x)

##### Killing the Connection: Automatically #####
# To end the connection, find the pid of the process
GrepResults<-system2("ps",c("ax | grep otherhost"),stdout=TRUE)
# Parse the pids from your grep into a numeric vector
Processes<-as.numeric(sub(" .*","",GrepResults)) 
# Kill all pids identified in the grep
tools::pskill(Processes)
Run Code Online (Sandbox Code Playgroud)