Secure Shell (SSH) Client for R
Currently the package is not available on CRAN:
devtools::install_github('ropensci/ssh')
Installation from source on MacOS or Linux requires libssh
(which is not libssh2
). On Debian or Ubuntu use libssh-dev:
sudo apt-get install -y libssh-dev
On Fedora we need libssh-devel:
sudo yum install libssh-devel
On CentOS / RHEL we install libssh-devel via EPEL:
sudo yum install epel-release
sudo yum install libssh-devel
On OS-X use libssh from Homebrew:
brew install libssh
First create an ssh session by connecting to an SSH server. You can either use private key or passphrase authentication:
session <- ssh_connect("[email protected]")
You can use the session in subsequent ssh functions below.
Run a command or script on the host while streaming stdout and stderr directly to the client.
ssh_exec_wait(session, command = c(
'curl -O https://cran.r-project.org/src/contrib/jsonlite_1.5.tar.gz',
'R CMD check jsonlite_1.5.tar.gz',
'rm -f jsonlite_1.5.tar.gz'
))
If you want to capture the stdout/stderr:
out <- ssh_exec_internal(session, "R -e 'rnorm(100)'")
cat(rawToChar(out$stdout))
Note that the exec functions are non interactive so they cannot prompt for a sudo password. A trick is to use -S
which reads the passord from stdin:
out <- ssh_exec_wait(session, 'echo "mypassword!" | sudo -s -S apt-get update -y')
Be very careful with hardcoding passwords!
Upload and download files via SCP. Directories are automatically traversed as in scp -r
.
# Upload a file to the server
file_path <- R.home("COPYING")
scp_upload(session, file_path)
# Download the file back and verify it is the same
scp_download(session, "COPYING", to = tempdir())
tools::md5sum(file_path)
tools::md5sum(file.path(tempdir(), "COPYING"))
Opens a port on your machine and tunnel all traffic to a custom target host via the SSH server.
ssh_tunnel(session, port = 5555,target = "ds043942.mongolab.com:43942")
This function blocks while the tunnel is active. Use the tunnel by connecting to localhost:5555
from a separate process. The tunnel can only be used once and will automatically be closed when the client disconnects.