Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify and close an SSH tunnel from R

Tags:

ssh

r

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!

like image 504
Steph Locke Avatar asked Nov 16 '25 03:11

Steph Locke


2 Answers

I found a nice article at Auto-closing SSH tunnels - it suggests using such code to connect:

ssh -f -L 3306:127.0.0.1:3306 [email protected] sleep 10;

It uses a feature that ssh will not close a connection while in use. It will first wait 10s - and if there the connection gets used close the connection once it is finished.

like image 50
bdecaf Avatar answered Nov 18 '25 21:11

bdecaf


On Mac and Linux you can close it as any other background ssh connection:

ps -ef | grep ssh

and then

kill -9 pid

I dont't know if there is ps on windows

like image 23
Rentrop Avatar answered Nov 18 '25 20:11

Rentrop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!