Art
Art

Reputation: 1335

How to close ssh (tunel) connection in R?

I have ssh + tunel connection executed like:

target <- paste0("host:3306")
ProxySev <- "[email protected]"
keyfile <- "path/to/key"
port <- 3307

cmd <- paste0('ssh::ssh_tunnel(ssh::ssh_connect(host = "', 
              ProxySev, '", keyfile ="', keyfile, '"), port = ', port, ', target = "', target, '")')

pid <- sys::r_background(
  args = c("-e", cmd),
  std_out = TRUE,
  std_err = TRUE
)

To close it I use tools::pskill(pid), but how to do that not knowing the pid? Eg without proper closing previous connection and trying to run again

pid <- sys::r_background(
  args = c("-e", cmd),
  std_out = TRUE,
  std_err = TRUE
)

I get the message:

Error: System failure for: bind() (Only one usage of each socket address (protocol/network address/port) is normally permitted)
Execution halted
Warning message:
Disconnecting from unused ssh session. Please use ssh_disconnect()

How to use ssh_disconnect() in such case? Or how to get pid of this background process? Thanks!

Upvotes: 0

Views: 34

Answers (1)

r2evans
r2evans

Reputation: 161110

I think you may be able to infer which process by using tools in the ps package. I'll demonstrate with Sys.sleep instead of an ssh connection, but the steps should be translatable.

pid <- sys::r_background(args=c("-e", "Sys.sleep(120)"), std_out = FALSE, std_err = FALSE)
procs <- ps::ps()
subset(procs, name == "Rterm.exe")
# # A tibble: 3 x 11
#     pid  ppid name      username    status       user   system        rss         vms created                 ps_handle 
#   <int> <int> <chr>     <chr>       <chr>       <dbl>    <dbl>      <dbl>       <dbl> <dttm>                  <I<list>> 
# 1 22284  4224 Rterm.exe "myhost\\r2" running    0.0938   0.0156   47214592    68915200 2022-09-21 12:43:32.263 <ps_handl>
# 2  8472 14464 Rterm.exe "myhost\\r2" running    6.5      0.719   267501568   281235456 2022-09-20 21:31:30.642 <ps_handl>
# 3  4224 14464 Rterm.exe "myhost\\r2" running 4768.     272.     1433354240 31551180800 2022-09-17 22:46:15.056 <ps_handl>
pids <- subset(procs, name == "Rterm.exe")$pid
lapply(setNames(nm = pids), function(pid) ps::ps_cmdline(ps::ps_handle(pid)))
# $`22284`
# [1] "c:\\R\\R-4.1.2\\bin\\x64\\Rterm" "-e"                              "Sys.sleep(120)"                 
# $`8472`
# [1] "c:\\R\\R-4.1.2\\bin\\x64\\Rterm.exe" "--ess"                               "--no-save"                          
# $`4224`
# [1] "c:\\R\\R-4.1.2\\bin\\x64\\Rterm.exe" "--ess"                               "--no-save"                          
(tools::pskill(22284))
# [1] TRUE

I wrapped pskill in parens since its return value (logical indicating if the process was found and killed) is invisible, the parens cause it to be printed.

Upvotes: 1

Related Questions