1

I'm trying to connect to a database that is located in an external server using dplyr's

src_postgres(dbname = NULL, host = NULL, port = NULL, user = NULL, 
                 password = NULL, ...)

So far so good, I've got all the parameters I need to connect to the database. The problem is that the server where the database is located requires an authentication too (username and password).

I tried creating a connection with ?pipe but seems like it only works when trying to extract files from a remote server.

Any clues?

2 Answers 2

1

Good news! I do this all the time and it's not hard :)

Two steps:

1. Create SSH key and put on remote server

from https://serverfault.com/posts/241593/edit

Generate ssh keys on your local machine:

$ ssh-keygen -t rsa -b 2048

And press Enter for empty passphrase to result in:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/username/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/username/.ssh/id_rsa.
Your public key has been saved in /home/username/.ssh/id_rsa.pub.

Copy your keys to the target server

ssh-copy-id id@server

Check that this worked with ssh 'id@server', and check folder .ssh/authorized_keys for the ssh keys.

You should know be able to log in with $ ssh id@server

2. Forward your database port to your local machine

You should know be able to use

ssh -fN id@server

to initiative an SSH connection and forward ports on to your local host. You may need to adjust the -p parameter to ssh to select the correct port.

Once you can successfully forward the port, you should be able to use src_postres() from your local machine to access the remote database.

You can also start your R script with

system("ssh -fN id@server")

or put the command in your .Rprofile

3. (optional)

Also, maybe you don't want your id and server address in your scripts, say, if you were going to give them to a client, or put them on github.

Then, edit or create file (on local machine) .ssh/config with the following content:

Host my_ssh
User id
Hostname server

and then you can just use ssh -fN my_ssh

0

the best way to do this is by connecting via DBI and then using the open connection with dplyr. For example:

library(DBI)
con <- dbConnect(RPostgres::Postgres())
db_table <- tbl(con, "my_table")
db_table %>%
  group_by(one_var) %>%
  tally()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.