I need to connect in R to a DB that uses an SSH tunnel. Based on googling SO tells me that I have to create an SSH tunnel first, then connect to my DB, but there is little on how to safely close the tunnel after executing my SQL.
Example:
if(!require(RPostgreSQL)) install.packages("RPostgreSQL")
# Create tunnel
myssh<-"ssh -f <server_user>@<server_ip> -L <unused_local_port>:localhost:<database_remote_port> -N"
system(myssh)
# Connect to DB
drv <- dbDriver("PostgreSQL")
conn <- dbConnect(
drv,
host = "127.0.0.1", user = "postgres",
password = "", dbname = "mydb",
)
# How to close tunnel?
How to correctly detect and close the SSH tunnel created by R?
PS I'm on Windows!