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
import os, tempfile, shutil, stat

# Create test files
test_dir = tempfile.mkdtemp(prefix='test_')
download_directory = tempfile.mkdtemp(prefix='download_')

with open(f"{test_dir}/test.txt", 'w') as f:
f.write('Hello from MorphCloud!')

os.makedirs(f"{test_dir}/subdir")
with open(f"{test_dir}/subdir/nested.txt", 'w') as f:
f.write('Nested file content')

# Transfer files
client = MorphCloudClient()
instance = client.instances.get("morphvm_abc123")

def upload_dir(sftp, local_path, remote_path):
try: sftp.mkdir(remote_path)
except: pass
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(sftp, local_item, remote_item)

def download_dir(sftp, 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(sftp, remote_item, local_item)

with instance.ssh() as ssh:
sftp = ssh._client.open_sftp()

try:
# Single file upload/download
sftp.put(f"{test_dir}/test.txt", "/tmp/test.txt")
sftp.get("/tmp/test.txt", f"{download_directory}/downloaded.txt")

# Directory upload/download
upload_dir(sftp, test_dir, "/tmp/upload_dir")
download_dir(sftp, "/tmp/upload_dir", f"{download_directory}/synced_dir")

finally:
sftp.close()

# Cleanup
shutil.rmtree(test_dir)
shutil.rmtree(download_directory)

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