微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

通过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)

原文地址:https://www.jb51.cc/postgresql/191934.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐