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

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

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

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

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

然后我连接到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")

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

但是,我想在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,"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.

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

按照@ r2evans的建议.
##### Starting the Connection #####
# Start the ssh connection to server "otherhost"
system2("ssh",c("-L8080:localhost:80","-N","-T","otherhost"),wait=FALSE)

您可以通过手动查找并键入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)

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...