Downloading Files into the Sandbox
Multiple ways to download files into a Lybic sandbox
This guide explains how to download files from external sources into a Lybic sandbox. Depending on your scenario and file type, you can choose the most suitable approach.
Method comparison
| Method | Best for | Supported OS | Pros | Limitations |
|---|---|---|---|---|
| FileCopy API (Recommended) | Smaller files | Windows/Linux/Android | Efficient, stable, supports multiple protocols | Requires an accessible URL |
| curl command | Large files, long downloads | Linux/Windows | Flexible, supports resume/partial download | Requires long-running task support |
| Write via stdin | Small text files (< 1MB) | Windows/Linux/Android | Simple, no external URL required | Only suitable for small files |
Method 1: FileCopy API (Recommended)
FileCopy API is the recommended way to download files into the sandbox. It supports downloading a file from an HTTP/HTTPS URL directly into a specified path inside the sandbox.
For full documentation, see: File Transfer
Basic usage
curl -X POST "https://api.lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/file/copy" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"files": [
{
"id": "download-dataset",
"src": {
"type": "httpGetLocation",
"url": "https://example.com/dataset.csv"
},
"dest": {
"type": "sandboxFileLocation",
"path": "/home/agent/data/dataset.csv"
}
}
]
}'import asyncio
from lybic import LybicClient, LybicAuth
from lybic.dto import (
SandboxFileCopyRequestDto,
FileCopyItem,
SandboxFileLocation,
HttpGetLocation
)
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.lybic.cn/"
)
) as client:
# Download a file into the sandbox
response = await client.sandbox.copy_files(
"SBX-xxxx",
SandboxFileCopyRequestDto(files=[
FileCopyItem(
id="download-dataset",
src=HttpGetLocation(
url="https://example.com/dataset.csv"
),
dest=SandboxFileLocation(
path="/home/agent/data/dataset.csv"
)
)
])
)
print("File downloaded successfully:", response)
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@lybic/core'
const lybic = new LybicClient({
baseUrl: 'https://api.lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
// Download a file into the sandbox
const result = await lybic.copyFilesWithSandbox('SBX-xxxx', {
files: [
{
id: 'download-dataset',
src: {
type: 'httpGetLocation',
url: 'https://example.com/dataset.csv',
},
dest: {
type: 'sandboxFileLocation',
path: '/home/agent/data/dataset.csv',
},
},
],
})
console.log('File downloaded successfully:', result.data)package main
import (
"context"
"fmt"
"github.com/lybic/lybic-sdk-go"
)
func main() {
ctx := context.Background()
client, _ := lybic.NewClient(nil)
copyDto := lybic.SandboxFileCopyRequestDto{
Files: []lybic.SandboxFileCopyRequestDtoFiles{
{
Id: "download-dataset",
Src: map[string]string{
"type": "httpGetLocation",
"url": "https://example.com/dataset.csv",
},
Dest: map[string]any{
"type": "sandboxFileLocation",
"path": "/home/agent/data/dataset.csv",
},
},
},
}
result, err := client.CopyFilesWithSandbox(ctx, "SBX-xxxx", copyDto)
if err != nil {
fmt.Println("Error downloading file:", err)
return
}
fmt.Printf("File downloaded successfully: %+v\n", result)
}Send custom headers
If the download requires authentication or custom headers:
curl -X POST "https://api.lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/file/copy" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"files": [
{
"id": "download-private-file",
"src": {
"type": "httpGetLocation",
"url": "https://storage.example.com/private/data.zip",
"headers": {
"Authorization": "Bearer STORAGE_TOKEN",
"X-Custom-Header": "custom-value"
}
},
"dest": {
"type": "sandboxFileLocation",
"path": "/home/agent/downloads/data.zip"
}
}
]
}'import asyncio
from lybic import LybicClient, LybicAuth
from lybic.dto import (
SandboxFileCopyRequestDto,
FileCopyItem,
SandboxFileLocation,
HttpGetLocation
)
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.lybic.cn/"
)
) as client:
response = await client.sandbox.copy_files(
"SBX-xxxx",
SandboxFileCopyRequestDto(files=[
FileCopyItem(
id="download-private-file",
src=HttpGetLocation(
url="https://storage.example.com/private/data.zip",
headers={
"Authorization": "Bearer STORAGE_TOKEN",
"X-Custom-Header": "custom-value"
}
),
dest=SandboxFileLocation(
path="/home/agent/downloads/data.zip"
)
)
])
)
print("Private file downloaded successfully:", response)
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@lybic/core'
const lybic = new LybicClient({
baseUrl: 'https://api.lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
const result = await lybic.copyFilesWithSandbox('SBX-xxxx', {
files: [
{
id: 'download-private-file',
src: {
type: 'httpGetLocation',
url: 'https://storage.example.com/private/data.zip',
headers: {
Authorization: 'Bearer STORAGE_TOKEN',
'X-Custom-Header': 'custom-value',
},
},
dest: {
type: 'sandboxFileLocation',
path: '/home/agent/downloads/data.zip',
},
},
],
})
console.log('Private file downloaded successfully:', result.data)package main
import (
"context"
"fmt"
"github.com/lybic/lybic-sdk-go"
)
func main() {
ctx := context.Background()
client, _ := lybic.NewClient(nil)
copyDto := lybic.SandboxFileCopyRequestDto{
Files: []lybic.SandboxFileCopyRequestDtoFiles{
{
Id: "download-private-file",
Src: map[string]any{
"type": "httpGetLocation",
"url": "https://storage.example.com/private/data.zip",
"headers": map[string]string{
"Authorization": "Bearer STORAGE_TOKEN",
"X-Custom-Header": "custom-value",
},
},
Dest: map[string]any{
"type": "sandboxFileLocation",
"path": "/home/agent/downloads/data.zip",
},
},
},
}
result, err := client.CopyFilesWithSandbox(ctx, "SBX-xxxx", copyDto)
if err != nil {
fmt.Println("Error downloading private file:", err)
return
}
fmt.Printf("Private file downloaded successfully: %+v\n", result)
}Download multiple files in batch
curl -X POST "https://api.lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/file/copy" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"files": [
{
"id": "download-model",
"src": {
"type": "httpGetLocation",
"url": "https://models.example.com/model.pth"
},
"dest": {
"type": "sandboxFileLocation",
"path": "/home/agent/models/model.pth"
}
},
{
"id": "download-config",
"src": {
"type": "httpGetLocation",
"url": "https://configs.example.com/config.yaml"
},
"dest": {
"type": "sandboxFileLocation",
"path": "/home/agent/configs/config.yaml"
}
},
{
"id": "download-dataset",
"src": {
"type": "httpGetLocation",
"url": "https://data.example.com/train.csv"
},
"dest": {
"type": "sandboxFileLocation",
"path": "/home/agent/data/train.csv"
}
}
]
}'import asyncio
from lybic import LybicClient, LybicAuth
from lybic.dto import (
SandboxFileCopyRequestDto,
FileCopyItem,
SandboxFileLocation,
HttpGetLocation
)
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.lybic.cn/"
)
) as client:
# Download multiple files in batch
response = await client.sandbox.copy_files(
"SBX-xxxx",
SandboxFileCopyRequestDto(files=[
FileCopyItem(
id="download-model",
src=HttpGetLocation(url="https://models.example.com/model.pth"),
dest=SandboxFileLocation(path="/home/agent/models/model.pth")
),
FileCopyItem(
id="download-config",
src=HttpGetLocation(url="https://configs.example.com/config.yaml"),
dest=SandboxFileLocation(path="/home/agent/configs/config.yaml")
),
FileCopyItem(
id="download-dataset",
src=HttpGetLocation(url="https://data.example.com/train.csv"),
dest=SandboxFileLocation(path="/home/agent/data/train.csv")
)
])
)
# Check the result of each file
for result in response.results:
if result.success:
print(f"✓ {result.id} downloaded successfully")
else:
print(f"✗ {result.id} download failed: {result.error}")
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@lybic/core'
const lybic = new LybicClient({
baseUrl: 'https://api.lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
// Download multiple files in batch
const result = await lybic.copyFilesWithSandbox('SBX-xxxx', {
files: [
{
id: 'download-model',
src: {
type: 'httpGetLocation',
url: 'https://models.example.com/model.pth',
},
dest: {
type: 'sandboxFileLocation',
path: '/home/agent/models/model.pth',
},
},
{
id: 'download-config',
src: {
type: 'httpGetLocation',
url: 'https://configs.example.com/config.yaml',
},
dest: {
type: 'sandboxFileLocation',
path: '/home/agent/configs/config.yaml',
},
},
{
id: 'download-dataset',
src: {
type: 'httpGetLocation',
url: 'https://data.example.com/train.csv',
},
dest: {
type: 'sandboxFileLocation',
path: '/home/agent/data/train.csv',
},
},
],
})
// Check the result of each file
result.data.results.forEach((r) => {
if (r.success) {
console.log(`✓ ${r.id} downloaded successfully`)
} else {
console.log(`✗ ${r.id} download failed: ${r.error}`)
}
})package main
import (
"context"
"fmt"
"github.com/lybic/lybic-sdk-go"
)
func main() {
ctx := context.Background()
client, _ := lybic.NewClient(nil)
copyDto := lybic.SandboxFileCopyRequestDto{
Files: []lybic.SandboxFileCopyRequestDtoFiles{
{
Id: "download-model",
Src: map[string]string{
"type": "httpGetLocation",
"url": "https://models.example.com/model.pth",
},
Dest: map[string]any{
"type": "sandboxFileLocation",
"path": "/home/agent/models/model.pth",
},
},
{
Id: "download-config",
Src: map[string]string{
"type": "httpGetLocation",
"url": "https://configs.example.com/config.yaml",
},
Dest: map[string]any{
"type": "sandboxFileLocation",
"path": "/home/agent/configs/config.yaml",
},
},
{
Id: "download-dataset",
Src: map[string]string{
"type": "httpGetLocation",
"url": "https://data.example.com/train.csv",
},
Dest: map[string]any{
"type": "sandboxFileLocation",
"path": "/home/agent/data/train.csv",
},
},
},
}
result, err := client.CopyFilesWithSandbox(ctx, "SBX-xxxx", copyDto)
if err != nil {
fmt.Println("Batch download failed:", err)
return
}
// Check the result of each file
for _, r := range result.Results {
if r.Success {
fmt.Printf("✓ %s downloaded successfully\n", r.Id)
} else {
fmt.Printf("✗ %s download failed: %s\n", r.Id, r.Error)
}
}
}Method 2: Using the curl command
If you need more flexible control, you can run curl directly inside the sandbox to download files. Since downloads can take a long time, you should combine this approach with long-running tasks.
For details, see: Executing Long-Running Asynchronous Tasks
Run curl downloads with systemd
# Run a download task with systemd --user run
curl -X POST "https://api.lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/process" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"executable": "systemd-run",
"args": [
"--user",
"--unit=download-large-file",
"--description=Download large file",
"curl",
"-L",
"-o",
"/home/agent/downloads/large-file.zip",
"https://example.com/large-file.zip"
]
}'import asyncio
from lybic import LybicClient, LybicAuth
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.lybic.cn/"
)
) as client:
# Start the download task
result = await client.sandbox.execute_process(
"SBX-xxxx",
executable="systemd-run",
args=[
"--user",
"--unit=download-large-file",
"--description=Download large file",
"curl",
"-L",
"-o",
"/home/agent/downloads/large-file.zip",
"https://example.com/large-file.zip"
]
)
print("Download task started:", result.stdout)
# Check task status
status = await client.sandbox.execute_process(
"SBX-xxxx",
executable="systemctl",
args=["--user", "status", "download-large-file"]
)
print("Task status:", status.stdout)
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@lybic/core'
const lybic = new LybicClient({
baseUrl: 'https://api.lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
// Start the download task
const result = await lybic.execSandboxProcess('SBX-xxxx', {
executable: 'systemd-run',
args: [
'--user',
'--unit=download-large-file',
'--description=Download large file',
'curl',
'-L',
'-o',
'/home/agent/downloads/large-file.zip',
'https://example.com/large-file.zip',
],
})
console.log('Download task started:', result.data.stdout)
// Check task status
const status = await lybic.execSandboxProcess('SBX-xxxx', {
executable: 'systemctl',
args: ['--user', 'status', 'download-large-file'],
})
console.log('Task status:', status.data.stdout)package main
import (
"context"
"fmt"
"github.com/lybic/lybic-sdk-go"
)
func main() {
ctx := context.Background()
client, _ := lybic.NewClient(nil)
// Start the download task
execDto := lybic.ExecSandboxProcessRequestDto{
Executable: "systemd-run",
Args: []string{
"--user",
"--unit=download-large-file",
"--description=Download large file",
"curl",
"-L",
"-o",
"/home/agent/downloads/large-file.zip",
"https://example.com/large-file.zip",
},
}
result, err := client.ExecSandboxProcess(ctx, "SBX-xxxx", execDto)
if err != nil {
fmt.Println("Error starting download task:", err)
return
}
fmt.Println("Download task started:", result.Stdout)
// Check task status
statusDto := lybic.ExecSandboxProcessRequestDto{
Executable: "systemctl",
Args: []string{"--user", "status", "download-large-file"},
}
status, err := client.ExecSandboxProcess(ctx, "SBX-xxxx", statusDto)
if err != nil {
fmt.Println("Error querying task status:", err)
return
}
fmt.Println("Task status:", status.Stdout)
}Download with a progress bar
# Use curl's progress bar
curl -X POST "https://api.lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/process" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"executable": "systemd-run",
"args": [
"--user",
"--unit=download-with-progress",
"bash",
"-c",
"curl -L --progress-bar -o /home/agent/downloads/dataset.tar.gz https://example.com/dataset.tar.gz 2>&1 | tee /home/agent/downloads/progress.log"
]
}'import asyncio
from lybic import LybicClient, LybicAuth
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.lybic.cn/"
)
) as client:
# Start a download task with progress
await client.sandbox.execute_process(
"SBX-xxxx",
executable="systemd-run",
args=[
"--user",
"--unit=download-with-progress",
"bash",
"-c",
"curl -L --progress-bar -o /home/agent/downloads/dataset.tar.gz "
"https://example.com/dataset.tar.gz 2>&1 | tee /home/agent/downloads/progress.log"
]
)
print("Download task started")
# Wait a bit, then check progress
await asyncio.sleep(5)
# Read progress log
log = await client.sandbox.execute_process(
"SBX-xxxx",
executable="tail",
args=["-n", "10", "/home/agent/downloads/progress.log"]
)
print("Download progress:", log.stdout)
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@lybic/core'
const lybic = new LybicClient({
baseUrl: 'https://api.lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
// Start a download task with progress
await lybic.execSandboxProcess('SBX-xxxx', {
executable: 'systemd-run',
args: [
'--user',
'--unit=download-with-progress',
'bash',
'-c',
'curl -L --progress-bar -o /home/agent/downloads/dataset.tar.gz ' +
'https://example.com/dataset.tar.gz 2>&1 | tee /home/agent/downloads/progress.log',
],
})
console.log('Download task started')
// Wait a bit, then check progress
await new Promise((resolve) => setTimeout(resolve, 5000))
// Read progress log
const log = await lybic.execSandboxProcess('SBX-xxxx', {
executable: 'tail',
args: ['-n', '10', '/home/agent/downloads/progress.log'],
})
console.log('Download progress:', log.data.stdout)package main
import (
"context"
"fmt"
"time"
"github.com/lybic/lybic-sdk-go"
)
func main() {
ctx := context.Background()
client, _ := lybic.NewClient(nil)
// Start a download task with progress
execDto := lybic.ExecSandboxProcessRequestDto{
Executable: "systemd-run",
Args: []string{
"--user",
"--unit=download-with-progress",
"bash",
"-c",
"curl -L --progress-bar -o /home/agent/downloads/dataset.tar.gz " +
"https://example.com/dataset.tar.gz 2>&1 | tee /home/agent/downloads/progress.log",
},
}
result, err := client.ExecSandboxProcess(ctx, "SBX-xxxx", execDto)
if err != nil {
fmt.Println("Error starting download task:", err)
return
}
fmt.Println("Download task started:", result.Stdout)
// Wait a bit, then check progress
time.Sleep(5 * time.Second)
// Read progress log
logDto := lybic.ExecSandboxProcessRequestDto{
Executable: "tail",
Args: []string{"-n", "10", "/home/agent/downloads/progress.log"},
}
log, err := client.ExecSandboxProcess(ctx, "SBX-xxxx", logDto)
if err != nil {
fmt.Println("Error reading progress log:", err)
return
}
fmt.Println("Download progress:", log.Stdout)
}Authenticated downloads
# Download with header-based authentication
curl -X POST "https://api.lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/process" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"executable": "systemd-run",
"args": [
"--user",
"--unit=download-authenticated",
"curl",
"-L",
"-H",
"Authorization: Bearer STORAGE_TOKEN",
"-o",
"/home/agent/downloads/private-data.zip",
"https://storage.example.com/private/data.zip"
]
}'import asyncio
from lybic import LybicClient, LybicAuth
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.lybic.cn/"
)
) as client:
# Download an authenticated file
result = await client.sandbox.execute_process(
"SBX-xxxx",
executable="systemd-run",
args=[
"--user",
"--unit=download-authenticated",
"curl",
"-L",
"-H",
"Authorization: Bearer STORAGE_TOKEN",
"-o",
"/home/agent/downloads/private-data.zip",
"https://storage.example.com/private/data.zip"
]
)
print("Authenticated download task started:", result.stdout)
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@lybic/core'
const lybic = new LybicClient({
baseUrl: 'https://api.lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
// Download an authenticated file
const result = await lybic.execSandboxProcess('SBX-xxxx', {
executable: 'systemd-run',
args: [
'--user',
'--unit=download-authenticated',
'curl',
'-L',
'-H',
'Authorization: Bearer STORAGE_TOKEN',
'-o',
'/home/agent/downloads/private-data.zip',
'https://storage.example.com/private/data.zip',
],
})
console.log('Authenticated download task started:', result.data.stdout)package main
import (
"context"
"fmt"
"github.com/lybic/lybic-sdk-go"
)
func main() {
ctx := context.Background()
client, _ := lybic.NewClient(nil)
// Download an authenticated file
execDto := lybic.ExecSandboxProcessRequestDto{
Executable: "systemd-run",
Args: []string{
"--user",
"--unit=download-authenticated",
"curl",
"-L",
"-H",
"Authorization: Bearer STORAGE_TOKEN",
"-o",
"/home/agent/downloads/private-data.zip",
"https://storage.example.com/private/data.zip",
},
}
result, err := client.ExecSandboxProcess(ctx, "SBX-xxxx", execDto)
if err != nil {
fmt.Println("Error starting authenticated download task:", err)
return
}
fmt.Println("Authenticated download task started:", result.Stdout)
}Method 3: Write small files via stdin
For small text files (usually less than 1MB), you can write content into a sandbox file directly via the stdinBase64 parameter.
Use cases
- Configuration files (JSON, YAML, INI, etc.)
- Script files (Python, shell, JavaScript, etc.)
- Text data files
- Environment variable files
Basic usage
# Base64-encode the file content
FILE_CONTENT=$(cat << 'EOF' | base64 -w0
{
"model": "gpt-4",
"temperature": 0.7,
"max_tokens": 2000
}
EOF
)
# Write the file into the sandbox
curl -X POST "https://api.lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/process" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"executable": "bash",
"args": ["-c", "cat > /home/agent/config/settings.json"],
"stdinBase64": "'$FILE_CONTENT'"
}'import asyncio
import base64
from lybic import LybicClient, LybicAuth
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.lybic.cn/"
)
) as client:
# Prepare config file content
config_content = """{
"model": "gpt-4",
"temperature": 0.7,
"max_tokens": 2000
}"""
# Base64 encode
stdin_data = base64.b64encode(config_content.encode()).decode()
# Write the file into the sandbox
result = await client.sandbox.execute_process(
"SBX-xxxx",
executable="bash",
args=["-c", "cat > /home/agent/config/settings.json"],
stdin_base64=stdin_data
)
print("Config file written successfully:", result.stdout)
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@lybic/core'
const lybic = new LybicClient({
baseUrl: 'https://api.lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
// Prepare config file content
const configContent = `{
"model": "gpt-4",
"temperature": 0.7,
"max_tokens": 2000
}`
// Base64 encode
const stdinData = Buffer.from(configContent).toString('base64')
// Write the file into the sandbox
const result = await lybic.execSandboxProcess('SBX-xxxx', {
executable: 'bash',
args: ['-c', 'cat > /home/agent/config/settings.json'],
stdinBase64: stdinData,
})
console.log('Config file written successfully:', result.data.stdout)package main
import (
"context"
"encoding/base64"
"fmt"
"github.com/lybic/lybic-sdk-go"
)
func main() {
ctx := context.Background()
client, _ := lybic.NewClient(nil)
// Prepare config file content
configContent := `{
"model": "gpt-4",
"temperature": 0.7,
"max_tokens": 2000
}`
// Base64 encode
stdinData := base64.StdEncoding.EncodeToString([]byte(configContent))
// Write the file into the sandbox
execDto := lybic.ExecSandboxProcessRequestDto{
Executable: "bash",
Args: []string{"-c", "cat > /home/agent/config/settings.json"},
StdinBase64: &stdinData,
}
result, err := client.ExecSandboxProcess(ctx, "SBX-xxxx", execDto)
if err != nil {
fmt.Println("Error writing config file:", err)
return
}
fmt.Println("Config file written successfully:", result.Stdout)
}Writing a script file
# Base64-encode the script content
SCRIPT_CONTENT=$(cat << 'EOF' | base64 -w0
#!/usr/bin/env python3
import sys
def main():
print("Hello from sandbox!")
print(f"Python version: {sys.version}")
if __name__ == "__main__":
main()
EOF
)
# Write the script and add execute permission
curl -X POST "https://api.lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/process" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"executable": "bash",
"args": ["-c", "cat > /home/agent/scripts/hello.py && chmod +x /home/agent/scripts/hello.py"],
"stdinBase64": "'$SCRIPT_CONTENT'"
}'import asyncio
import base64
from lybic import LybicClient, LybicAuth
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.lybic.cn/"
)
) as client:
# Prepare script content
script_content = """#!/usr/bin/env python3
import sys
def main():
print("Hello from sandbox!")
print(f"Python version: {sys.version}")
if __name__ == "__main__":
main()
"""
# Base64 encode
stdin_data = base64.b64encode(script_content.encode()).decode()
# Write the script and add execute permission
await client.sandbox.execute_process(
"SBX-xxxx",
executable="bash",
args=["-c", "cat > /home/agent/scripts/hello.py && chmod +x /home/agent/scripts/hello.py"],
stdin_base64=stdin_data
)
print("Script file written successfully")
# Verify that the script can run
run_result = await client.sandbox.execute_process(
"SBX-xxxx",
executable="python3",
args=["/home/agent/scripts/hello.py"]
)
print("Script output:", run_result.stdout)
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@lybic/core'
const lybic = new LybicClient({
baseUrl: 'https://api.lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
// Prepare script content
const scriptContent = `#!/usr/bin/env python3
import sys
def main():
print("Hello from sandbox!")
print(f"Python version: {sys.version}")
if __name__ == "__main__":
main()
`
// Base64 encode
const stdinData = Buffer.from(scriptContent).toString('base64')
// Write the script and add execute permission
await lybic.execSandboxProcess('SBX-xxxx', {
executable: 'bash',
args: ['-c', 'cat > /home/agent/scripts/hello.py && chmod +x /home/agent/scripts/hello.py'],
stdinBase64: stdinData,
})
console.log('Script file written successfully')
// Verify that the script can run
const runResult = await lybic.execSandboxProcess('SBX-xxxx', {
executable: 'python3',
args: ['/home/agent/scripts/hello.py'],
})
console.log('Script output:', runResult.data.stdout)package main
import (
"context"
"encoding/base64"
"fmt"
"github.com/lybic/lybic-sdk-go"
)
func main() {
ctx := context.Background()
client, _ := lybic.NewClient(nil)
// Prepare script content
scriptContent := `#!/usr/bin/env python3
import sys
def main():
print("Hello from sandbox!")
print(f"Python version: {sys.version}")
if __name__ == "__main__":
main()
`
// Base64 encode
stdinData := base64.StdEncoding.EncodeToString([]byte(scriptContent))
// Write the script and add execute permission
execDto := lybic.ExecSandboxProcessRequestDto{
Executable: "bash",
Args: []string{"-c", "cat > /home/agent/scripts/hello.py && chmod +x /home/agent/scripts/hello.py"},
StdinBase64: &stdinData,
}
result, err := client.ExecSandboxProcess(ctx, "SBX-xxxx", execDto)
if err != nil {
fmt.Println("Error writing script file:", err)
return
}
fmt.Println("Script file written successfully")
// Verify that the script can run
runDto := lybic.ExecSandboxProcessRequestDto{
Executable: "python3",
Args: []string{"/home/agent/scripts/hello.py"},
}
runResult, err := client.ExecSandboxProcess(ctx, "SBX-xxxx", runDto)
if err != nil {
fmt.Println("Error running script:", err)
return
}
fmt.Println("Script output:", runResult.Stdout)
}Writing multi-line configuration files
# Base64-encode a YAML config
YAML_CONTENT=$(cat << 'EOF' | base64 -w0
database:
host: localhost
port: 5432
name: myapp
user: admin
password: secret
redis:
host: localhost
port: 6379
db: 0
logging:
level: INFO
format: json
EOF
)
# Write the config file
curl -X POST "https://api.lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/process" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"executable": "bash",
"args": ["-c", "cat > /home/agent/config/app.yaml"],
"stdinBase64": "'$YAML_CONTENT'"
}'import asyncio
import base64
from lybic import LybicClient, LybicAuth
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.lybic.cn/"
)
) as client:
# Prepare YAML config content
yaml_content = """database:
host: localhost
port: 5432
name: myapp
user: admin
password: secret
redis:
host: localhost
port: 6379
db: 0
logging:
level: INFO
format: json
"""
# Base64 encode
stdin_data = base64.b64encode(yaml_content.encode()).decode()
# Write the config file
await client.sandbox.execute_process(
"SBX-xxxx",
executable="bash",
args=["-c", "cat > /home/agent/config/app.yaml"],
stdin_base64=stdin_data
)
print("YAML config file written successfully")
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@lybic/core'
const lybic = new LybicClient({
baseUrl: 'https://api.lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
// Prepare YAML config content
const yamlContent = `database:
host: localhost
port: 5432
name: myapp
user: admin
password: secret
redis:
host: localhost
port: 6379
db: 0
logging:
level: INFO
format: json
`
// Base64 encode
const stdinData = Buffer.from(yamlContent).toString('base64')
// Write the config file
await lybic.execSandboxProcess('SBX-xxxx', {
executable: 'bash',
args: ['-c', 'cat > /home/agent/config/app.yaml'],
stdinBase64: stdinData,
})
console.log('YAML config file written successfully')package main
import (
"context"
"encoding/base64"
"fmt"
"github.com/lybic/lybic-sdk-go"
)
func main() {
ctx := context.Background()
client, _ := lybic.NewClient(nil)
// Prepare YAML config content
yamlContent := `database:
host: localhost
port: 5432
name: myapp
user: admin
password: secret
redis:
host: localhost
port: 6379
db: 0
logging:
level: INFO
format: json
`
// Base64 encode
stdinData := base64.StdEncoding.EncodeToString([]byte(yamlContent))
// Write the config file
execDto := lybic.ExecSandboxProcessRequestDto{
Executable: "bash",
Args: []string{"-c", "cat > /home/agent/config/app.yaml"},
StdinBase64: &stdinData,
}
result, err := client.ExecSandboxProcess(ctx, "SBX-xxxx", execDto)
if err != nil {
fmt.Println("Error writing YAML config file:", err)
return
}
fmt.Println("YAML config file written successfully")
}Best practices
Choose the right method
-
Most cases: use the FileCopy API
- Pros: efficient, stable, supports all platforms
- Requires: the file has an accessible HTTP(S) URL
-
Very large files or special needs: use the
curlcommand- Pros: flexible control, supports resume
- Requires: a Linux sandbox, used together with long-running tasks
-
Small config files: write via stdin
- Pros: simple and direct, no external URL
- Limitation: only suitable for small files (< 1MB)
Error handling
It is recommended to verify the file after downloading:
# Verify the file exists and is non-empty
curl -X POST "https://api.lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/process" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"executable": "bash",
"args": ["-c", "test -s /home/agent/downloads/file.zip && echo \"Download succeeded\" || echo \"Download failed\""]
}'import asyncio
import base64
from lybic import LybicClient, LybicAuth
async def verify_file_download(client, sandbox_id, file_path):
"""Verify the file exists and is non-empty."""
result = await client.sandbox.execute_process(
sandbox_id,
executable="bash",
args=["-c", f"test -s {file_path} && echo 'FILE_EXISTS' || echo 'FILE_MISSING'"]
)
stdout = base64.b64decode(result.stdoutBase64 or '').decode(errors='ignore')
return 'FILE_EXISTS' in stdout
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.lybic.cn/"
)
) as client:
# Download file
await client.sandbox.copy_files("SBX-xxxx", ...)
# Verify download
if await verify_file_download(client, "SBX-xxxx", "/home/agent/downloads/file.zip"):
print("✓ Download verification succeeded")
else:
print("✗ Download verification failed")
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@lybic/core'
async function verifyFileDownload(
lybic: LybicClient,
sandboxId: string,
filePath: string
): Promise<boolean> {
const result = await lybic.execSandboxProcess(sandboxId, {
executable: 'bash',
args: ['-c', `test -s ${filePath} && echo 'FILE_EXISTS' || echo 'FILE_MISSING'`],
})
return atob(result.data?.stdoutBase64 || '').includes('FILE_EXISTS')
}
const lybic = new LybicClient({
baseUrl: 'https://api.lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
// Download file
await lybic.copyFilesWithSandbox('SBX-xxxx', { ... })
// Verify download
if (await verifyFileDownload(lybic, 'SBX-xxxx', '/home/agent/downloads/file.zip')) {
console.log('✓ Download verification succeeded')
} else {
console.log('✗ Download verification failed')
}package main
import (
"context"
"fmt"
"base64"
"strings"
"github.com/lybic/lybic-sdk-go"
)
func verifyFileDownload(ctx context.Context, client *lybic.Client, sandboxID, filePath string) (bool, error) {
execDto := lybic.ExecSandboxProcessRequestDto{
Executable: "bash",
Args: []string{"-c", fmt.Sprintf("test -s %s && echo 'FILE_EXISTS' || echo 'FILE_MISSING'", filePath)},
}
result, err := client.ExecSandboxProcess(ctx, sandboxID, execDto)
if err != nil {
return false, err
}
stdout, _ := base64.StdEncoding.DecodeString(result.StdoutBase64)
return strings.Contains(string(stdout), "FILE_EXISTS"), nil
}
func main() {
ctx := context.Background()
client, _ := lybic.NewClient(nil)
// Download file
// ...
// Verify download
success, err := verifyFileDownload(ctx, client, "SBX-xxxx", "/home/agent/downloads/file.zip")
if err != nil {
fmt.Println("Verification error:", err)
return
}
if success {
fmt.Println("✓ Download verification succeeded")
} else {
fmt.Println("✗ Download verification failed")
}
}Security recommendations
- Use HTTPS: make sure download links use HTTPS
- Verify files: validate file integrity after download (checksum, file size, etc.)
- Permission control: set appropriate file permissions to avoid exposing sensitive files
- Temporary URLs: for sensitive files, use time-limited presigned URLs
Related docs
- File Transfer API - Full documentation for the FileCopy API
- Executing Long-Running Asynchronous Tasks - Running long tasks with systemd
- Running commands and executing code -
execSandboxProcessAPI documentation