Skip to main content

File Transfer

SSH enables secure file transfers between your local machine and Morph instances using SFTP.

from morphcloud.api import MorphCloudClient

client = MorphCloudClient()
instance = client.instances.get("morphvm_abc123")

with instance.ssh() as ssh:
# Get SFTP client
sftp = ssh._client.open_sftp()
try:
# Upload a file
sftp.put("/local/path/file.txt", "/remote/path/file.txt")

# Download a file
sftp.get("/remote/path/file.txt", "/local/path/file.txt")

# Upload directory recursively
def upload_dir(local_path, remote_path):
sftp.mkdir(remote_path)
for item in os.listdir(local_path):
local_item = os.path.join(local_path, item)
remote_item = f"{remote_path}/{item}"
if os.path.isfile(local_item):
sftp.put(local_item, remote_item)
else:
upload_dir(local_item, remote_item)

upload_dir("/local/dir", "/remote/dir")

# Download directory recursively
def download_dir(remote_path, local_path):
os.makedirs(local_path, exist_ok=True)
for item in sftp.listdir_attr(remote_path):
remote_item = f"{remote_path}/{item.filename}"
local_item = os.path.join(local_path, item.filename)
if stat.S_ISREG(item.st_mode):
sftp.get(remote_item, local_item)
elif stat.S_ISDIR(item.st_mode):
download_dir(remote_item, local_item)

download_dir("/remote/dir", "/local/dir")

finally:
sftp.close()

Notes:

  • The CLI's copy command provides better progress indication and error handling than manual SFTP operations
  • Both source and destination paths use the format instance_id:/path for remote paths
  • When copying to an instance without specifying a full path, files go to the user's home directory
  • The -r or --recursive flag is required for directory copies