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

前端之家收集整理的这篇文章主要介绍了通过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)

猜你在找的Postgre SQL相关文章