Command Execution
Execute shell commands and system operations within secure sandbox boundaries with comprehensive monitoring and controls.
Command Execution
Execute shell commands and system operations securely within isolated sandbox environments with comprehensive safety controls and monitoring.
⚠️ Restricted Command Environment
Command execution is heavily restricted and monitored. Only safe, pre-approved commands are allowed to ensure system security and stability.
Overview
The Command Execution tool provides secure shell command execution capabilities within the sandbox environment, enabling system operations, file management, and utility commands while maintaining strict security boundaries.
Key Features
- Command Whitelist - Only pre-approved, safe commands are permitted
- Argument Validation - All command arguments are validated and sanitized
- Output Monitoring - Real-time monitoring of command execution and output
- Resource Controls - CPU, memory, and execution time limits enforced
- Security Isolation - Commands run in isolated containers with restricted permissions
Methods
commandExecution
Execute shell commands securely within the sandbox environment.
| Parameter | Type | Required | Description |
|---|---|---|---|
| command | String | Yes | The command to execute |
| args | Array | No | Optional command arguments |
| workingDirectory | String | No | Working directory for execution |
| timeout | Number | No | Execution timeout in seconds (max: 300, default: 60) |
| environment | Object | No | Environment variables as key-value pairs |
{
"command": "ls",
"args": ["-la", "/sandbox/data"],
"workingDirectory": "/sandbox",
"timeout": 30,
"environment": {
"CUSTOM_VAR": "value"
}
}Output:
stdout(String) - Standard output from commandstderr(String) - Standard error outputexitCode(Number) - Command exit codeexecutionTime(Number) - Execution duration in millisecondsresourceUsage(Object) - CPU, memory, and disk usage statistics
Supported Commands
File Operations
Text Processing
Archive Operations
📦 Archive Size Limits
Archive operations are subject to size limits and file count restrictions for security and performance.
Supported Commands:
tar- Archive creation and extractiongzip/gunzip- Compression and decompressionzip/unzip- ZIP archive operations
Security Controls:
- Archive size validation (max: 500MB)
- File count limits (max: 10,000 files)
- Path validation during extraction
- Compression ratio monitoring
Examples:
# Create compressed archive
tar -czf /sandbox/output/backup.tar.gz /sandbox/data/
# Extract archive safely
tar -xzf /sandbox/input/data.tar.gz -C /sandbox/working/
# ZIP operations
zip -r /sandbox/output/report.zip /sandbox/reports/
unzip /sandbox/input/package.zip -d /sandbox/extracted/System Information
Supported Commands:
ps- Process information (sandbox only)df- Disk space usage (sandbox filesystem)free- Memory usage informationuname- System information (limited)whoami- Current user information
Information Scope:
- Limited to sandbox environment
- System details filtered
- Resource usage within sandbox
Examples:
# Check available disk space
df -h /sandbox
# Monitor memory usage
free -h
# Process information
ps aux | head -10Network Tools
🌐 Network Restrictions
Network tools have strict destination restrictions and are limited to approved endpoints only.
Supported Commands:
ping- Network connectivity testing (restricted destinations)curl- HTTP requests (HTTPS only, approved domains)wget- File downloads (size and destination limited)
Network Policies:
- HTTPS-only connections
- Approved destination whitelist
- Download size limits (max: 100MB)
- Request rate limiting
Examples:
# Test connectivity
ping -c 4 api.example.com
# HTTP requests
curl -s "https://api.github.com/repos/owner/repo" | head -20
# Download files
wget "https://example.com/data.csv" -O /sandbox/data/downloaded.csvSecurity Architecture
Command Validation Pipeline
Execution Environment
Container Isolation:
- Each command runs in isolated container
- Restricted filesystem access
- Limited network connectivity
- Process isolation enforced
Resource Controls:
- CPU usage limits (2 cores max)
- Memory restrictions (1GB max)
- Execution timeout (5 minutes default)
- Disk I/O rate limiting
Security Monitoring:
- Real-time command monitoring
- Output content validation
- Resource usage tracking
- Security violation detection
Error Handling
Common Error Scenarios
| Error Type | Cause | Resolution |
|---|---|---|
| Command Not Found | Command not in whitelist | Use supported commands only |
| Permission Denied | Insufficient privileges | Check file/directory permissions |
| Resource Limit Exceeded | CPU/Memory/Time limits | Optimize command or request more resources |
| Network Access Denied | Blocked destination | Use approved endpoints only |
| Path Access Violation | Directory traversal attempt | Use paths within sandbox only |
Error Response Format
{
"type": "COMMAND_NOT_ALLOWED",
"message": "The specified command is not allowed in the sandbox environment",
"details": {
"command": "rm -rf /",
"errorCode": "CMD_BLOCKED",
"suggestions": [
"Use 'rm filename' to remove specific files",
"Check the supported commands list",
"Ensure paths are within sandbox directory"
]
}
}Best Practices
💡 Command Execution Best Practices
Security Guidelines
- Command Validation - Always validate command syntax before execution
- Path Verification - Use absolute paths within sandbox directory
- Output Handling - Check command exit codes and error output
- Resource Monitoring - Monitor resource usage for long-running commands
Performance Optimization
- Batch Operations - Combine multiple operations when possible
- Efficient Commands - Use appropriate tools for data size
- Output Streaming - Process large outputs in chunks
- Cleanup Operations - Remove temporary files after use
Error Recovery
- Graceful Handling - Implement proper error handling for all commands
- Retry Logic - Add retry mechanisms for transient failures
- Fallback Options - Provide alternative approaches for failed operations
- Logging - Maintain detailed logs for debugging
Usage Examples
File Processing Workflow
#!/bin/bash
# Data processing pipeline
# Create working directories
mkdir -p /sandbox/working/processed
# Process CSV data
awk -F',' 'NR>1 {sum+=$3} END {print "Total:", sum}' /sandbox/data/sales.csv
# Generate report
{
echo "Data Processing Report"
echo "===================="
echo "Processing Date: $(date)"
echo "Files Processed:"
ls -la /sandbox/data/*.csv
echo ""
echo "Summary Statistics:"
wc -l /sandbox/data/*.csv
} > /sandbox/output/processing_report.txt
# Archive results
tar -czf /sandbox/output/results_$(date +%Y%m%d).tar.gz /sandbox/working/processed/
echo "Processing completed successfully"Log Analysis Example
#!/bin/bash
# Log analysis and monitoring
LOG_FILE="/sandbox/logs/application.log"
OUTPUT_DIR="/sandbox/analysis"
# Create analysis directory
mkdir -p "$OUTPUT_DIR"
# Extract error patterns
grep -i "error\|exception\|failed" "$LOG_FILE" > "$OUTPUT_DIR/errors.log"
# Count occurrences
echo "Error Summary:" > "$OUTPUT_DIR/summary.txt"
grep -c -i "error" "$LOG_FILE" | sed 's/^/Errors: /' >> "$OUTPUT_DIR/summary.txt"
grep -c -i "warning" "$LOG_FILE" | sed 's/^/Warnings: /' >> "$OUTPUT_DIR/summary.txt"
# Top error messages
echo "Most Common Errors:" >> "$OUTPUT_DIR/summary.txt"
grep -i "error" "$LOG_FILE" | sort | uniq -c | sort -nr | head -10 >> "$OUTPUT_DIR/summary.txt"
# Generate timestamp analysis
awk '{print substr($1,1,10)}' "$LOG_FILE" | sort | uniq -c > "$OUTPUT_DIR/daily_counts.txt"
echo "Log analysis completed"Integration Patterns
With Code Execution Tools
import subprocess
import os
def execute_system_command(command, args=None):
"""Execute system commands from Python code."""
try:
if args:
full_command = [command] + args
else:
full_command = command.split()
result = subprocess.run(
full_command,
capture_output=True,
text=True,
timeout=30,
cwd='/sandbox/workspace'
)
return {
'stdout': result.stdout,
'stderr': result.stderr,
'returncode': result.returncode
}
except subprocess.TimeoutExpired:
return {'error': 'Command execution timeout'}
except Exception as e:
return {'error': f'Execution failed: {str(e)}'}
# Example usage
result = execute_system_command('ls', ['-la', '/sandbox/data'])
if result.get('returncode') == 0:
print("Files:", result['stdout'])
else:
print("Error:", result.get('stderr', result.get('error')))With File System Tools
# Workflow: Process uploaded files
UPLOAD_DIR="/sandbox/uploads"
PROCESS_DIR="/sandbox/processing"
OUTPUT_DIR="/sandbox/output"
# Setup directories
mkdir -p "$PROCESS_DIR" "$OUTPUT_DIR"
# Process each uploaded file
for file in "$UPLOAD_DIR"/*; do
if [[ -f "$file" ]]; then
filename=$(basename "$file")
echo "Processing: $filename"
# Determine file type and process accordingly
case "${filename##*.}" in
"csv")
# Process CSV file
awk -F',' '{print NF}' "$file" | sort -nu | tail -1 > "$OUTPUT_DIR/${filename%.csv}_columns.txt"
;;
"txt")
# Process text file
wc -l "$file" > "$OUTPUT_DIR/${filename%.txt}_stats.txt"
;;
*)
echo "Unsupported file type: $filename"
;;
esac
fi
done
echo "File processing completed"Troubleshooting
Performance Issues
🔧 Performance Troubleshooting
Common Issues:
- Slow Execution: Commands taking longer than expected
- Memory Errors: Commands failing due to memory constraints
- Timeout Errors: Commands exceeding execution time limits
Solutions:
- Use more efficient command alternatives
- Process data in smaller chunks
- Optimize command arguments and flags
- Monitor resource usage during execution
Security Violations
Blocked Commands:
- Commands not in the approved whitelist are automatically blocked
- System administration commands are restricted
- Network commands to unapproved destinations are denied
Resolution Steps:
- Check command against supported command list
- Verify arguments and paths are within sandbox
- Ensure network destinations are approved
- Contact support for additional command requirements
Related Tools
Code Execution
Execute Python and JavaScript code with command integration capabilities
Package Installer
Install system packages and utilities for command line operations
File System Tools
Manage files and directories with comprehensive CRUD operations
Next Steps: Explore Package Installer for dependency management, or see File System Tools for comprehensive file operations.