2016-07-05 15 views
6

Come parte del mio flusso di lavoro R per uno dei miei progetti, carico i dati da una tabella PostgreSQL situata su un server remoto.Creare un tunnel SSH su un altro computer tramite R per accedere alla tabella postgreSQL

Il mio codice è simile a questo (credenziali anonime).

ho aprire una connessione ssh al server remoto in terminal.

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

Ho quindi connettersi al database Postgres in 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") 

Questo approccio funziona bene, e sono in grado di scaricare i dati senza problemi.

Tuttavia, vorrei fare il primo passo, cioè creare la connessione ssh, in R piuttosto che in terminale. Ecco il mio tentativo di farlo, con errore di accompagnamento.

# 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. 

di chiarire la mia domanda, vorrei eseguire questo intero flusso di lavoro (stabilire una connessione, scaricare i dati PostgreSQL) interamente in R, senza alcun passo in terminale.

+2

'system2 ("ssh", c ("- L8080: localhost: 80", "-N", "-T", "otherhost"), wait = FALSE) 'ha funzionato per me su linux. Non funziona su Windows, tuttavia, probabilmente a causa della mancanza di 'fork', quindi potresti aver bisogno di qualcosa in background (come' parallel' o ['future'] (https://github.com/HenrikBengtsson/future) per eseguire un'altra sessione R). L'arresto potrebbe funzionare con 'tools :: pskill', non sono stati testati. – r2evans

+0

@ r2evans Ha funzionato per me, grazie. – Andy

risposta

2

Come da @ r2evans suggerimenti.

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

Si può uccidere il processo di trovando e digitando manualmente nel pid o automaticamente uccidendo tutti i PID che corrispondono il nome del server. Si avverte che si desidera utilizzare quest'ultima versione solo se si utilizza un nome server relativamente univoco che è improbabile che venga duplicato in altri processi.

##### 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) 
0

In alternativa è possibile utilizzare plink con shell

library(RPostgreSQL) 
drv <- dbDriver("PostgreSQL") 

cmd<- paste0(
    "plink ", 
    # use key and run in background process 
    " -i ../.ssh/id_rsa -N -batch -ssh", 
    # port forwarding 
    " -L 5432:127.0.0.1:5432", 
    # location of db 
    " [email protected]" 
) 

shell(cmd, wait=FALSE) 
# sleep a while before the the connection been established. 
Sys.sleep(5) 

conn <- dbConnect(
    drv, 
    host = "127.0.0.1", 
    port=5432, 
    dbname="mydb", 
    password = "pass" 
) 

dbListTables(conn) 
Problemi correlati