Skip to content

Description:

  • Interact with data via ssh and python

Resources:

This notebook reads its settings from environment variables. Set them before starting Jupyter:

  • SSH_HOST: hostname of your SSH server
  • SSH_PORT: optional, defaults to 22
  • SSH_USER: SSH user name
  • SSH_PASSWORD: password for that user
  • SSH_PRIVATE_KEY_PATH: path to that user’s private key file

SSH_PASSWORD is used by Example 1 only; SSH_PORT and SSH_PRIVATE_KEY_PATH by Examples 2-4.

Connect with a password

# NOTE!: using `open` will cause collisions. It **must** be aliased.
import os
from fsspec import open as fs_open
from sshfs import SSHFileSystem
fs = SSHFileSystem(
os.environ["SSH_HOST"],
username=os.environ["SSH_USER"],
password=os.environ["SSH_PASSWORD"]
)
details = fs.info('/tmp')

Connect with a private key

import os
from sshfs import SSHFileSystem
ssh_user = os.environ["SSH_USER"]
fs = SSHFileSystem(
host=os.environ["SSH_HOST"],
port=int(os.environ.get("SSH_PORT", "22")),
username=ssh_user,
client_keys=[os.environ["SSH_PRIVATE_KEY_PATH"]]
)

List contents in a remote directory via ssh

fs.ls(f"/home/{ssh_user}")

Download the contents of a remote directory to local via ssh

from pathlib import Path
Path("/tmp/ganymede_demo").mkdir(parents=True, exist_ok=True)
# Change rpath to a file that exists on your remote host
fs.get(rpath=f"/home/{ssh_user}/example.jpeg", lpath="/tmp/ganymede_demo/example.jpeg")

ganymede is made by Eugo