A secure Python code execution library with dual-mode architecture: run code locally for fast development or connect to a remote API server for production workloads. Perfect for AI agents, code playgrounds, and educational platforms.
- π Local Execution: Direct subprocess execution for fast iteration and debugging
- π Remote Execution: HTTP client for connecting to sandbox API servers
- π Unified Interface: Same API works for both local and remote modes
- π€ AI Agent Ready: Easy integration with LangChain, AutoGen, and custom agents
- Multi-layered Security: AST validation, resource limits, network control
- π File I/O Support: Upload input files and retrieve output files
- β‘ Platform Agnostic: Works on Linux, Windows, macOS, Docker, Kubernetes, and serverless
Best for: Development, debugging, fast iteration, local AI agents
How it works: Executes code directly on your machine using subprocess isolation
Installation:
pip install sandbox-executorExample:
from sandbox_executor import SandboxClient
# Create client without server_url = local execution
client = SandboxClient()
code = """
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
result = [fibonacci(i) for i in range(10)]
print("Fibonacci:", result)
"""
result = client.execute(code)
print(result.stdout)
# Output: Fibonacci: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]Advantages:
- β‘ Fastest: No network overhead
- π Easy debugging: Direct execution with full error messages
- π§ Simple setup: No server required
- π» Offline capable: Works without internet
Use cases:
- Local development and testing
- AI agent prototyping
- Educational tools
- Code snippets execution
- Quick scripts and automation
Best for: Production, scaling, untrusted code, multi-tenant systems
How it works: Sends code to a remote API server via HTTP requests
Installation: Step 1: Run Sandbox server (on docker or K8s cluster)
git clone https://github.com/dinhhungitsoft/secure-python-sandbox
cd secure-python-sandbox
# Run API server on docker
docker-compose up # Serving at http://localhost:8000Step 2: Install the client library in your main project
pip install sandbox-executorStep 3: Initialize the sandbox client with the Sandbox server endpoint
from sandbox_executor import SandboxClient
# Create client with server_url = remote execution
client = SandboxClient(
server_url="http://localhost:8000",
timeout=30
)
code = """
import math
radius = 5
area = math.pi * radius ** 2
print(f"Circle area: {area:.2f}")
"""
result = client.execute(code)
print(result.stdout)
# Output: Circle area: 78.54Advantages:
- π Enhanced security: Code runs in isolated containers
- π Scalable: Handle multiple concurrent executions
- π Distributed: Execute code on powerful remote machines
- π‘οΈ Better isolation: Full container-level isolation
Use cases:
- Production AI agents
- Multi-tenant code execution platforms
- Online code playgrounds
- Serverless functions
- Educational platforms with many users
π Notes for Maximum Security Deployment: For the highest level of isolation and security, deploy the sandbox API on a Kubernetes cluster with Kata Containers runtime. Kata Containers provide lightweight VMs that offer hardware-level isolation while maintaining container compatibility, making them ideal for executing untrusted code in multi-tenant environments.
Create a .env file:
SANDBOX_MODE=secure
SANDBOX_TIMEOUT=30
SANDBOX_ALLOW_NETWORK=falseLoad automatically:
client = SandboxClient.from_env()from sandbox_executor import SandboxClient
client = SandboxClient()
# Provide input files
input_files = {
"data.csv": b"id,value\n1,100\n2,200\n3,300\n"
}
code = """
import csv
# Read CSV
with open('data.csv', 'r') as f:
reader = csv.DictReader(f)
data = list(reader)
# Calculate total
total = sum(int(row['value']) for row in data)
print(f"Total: {total}")
# Write output
with open('result.txt', 'w') as f:
f.write(f"Sum: {total}\\n")
"""
result = client.execute(code, input_files=input_files)
print(result.stdout) # Total: 600
# Get output file
output = result.get_file_content('result.txt')
print(output.decode()) # Sum: 600Once the server is running, visit:
- Swagger UI: http://localhost:8000/docs
curl http://localhost:8000/curl -X POST http://localhost:8000/execute \
-H "Content-Type: application/json" \
-d '{
"code": "print(\"Hello, World!\")",
"timeout": 30,
"allow_network": false
}'βββββββββββββββββββββββββββββββββββββββ
β 1. AST Validation β Compile-time filtering
βββββββββββββββββββββββββββββββββββββββ€
β 2. Import Restrictions β Module whitelist/blacklist
βββββββββββββββββββββββββββββββββββββββ€
β 3. Resource Limits β CPU, Memory, Processes
βββββββββββββββββββββββββββββββββββββββ€
β 4. Filesystem Isolation β Temporary directory sandbox
βββββββββββββββββββββββββββββββββββββββ€
β 5. Network Blocking β Socket monkey-patching
βββββββββββββββββββββββββββββββββββββββ€
β 6. Execution Timeout β Hard timeout enforcement
βββββββββββββββββββββββββββββββββββββββ
Secure Mode (Default):
- AST validation and restricted imports
- Resource limits (CPU, memory, processes)
- Filesystem isolation with temporary directories
- Network blocking (configurable)
- Execution timeout enforcement
Simple Mode:
- Basic subprocess isolation
- Timeout and output limits
- Suitable for trusted code
See the examples/ directory for complete examples:
basic_usage.py- Basic execution patternsclient_usage.py- Local vs Remote client usageagent_integration.py- AI agent integration exampleswith_files.py- Working with input/output filessecurity_tests.py- Security feature demonstrations
Run examples:
python examples/basic_usage.py
python examples/client_usage.py
python examples/agent_integration.pyConfigure the sandbox behavior using environment variables (in .env):
| Variable | Default | Description |
|---|---|---|
SANDBOX_MODE |
secure |
Execution mode: secure or simple |
SANDBOX_TIMEOUT |
30 |
Default execution timeout (seconds) |
SANDBOX_ALLOW_NETWORK |
false |
Allow network access by default |
The secure executor includes configurable whitelists and blacklists:
Safe Modules (allowed by default):
math,random,datetime,json,base64,hashlibcollections,itertools,functools,re,stringdecimal,fractions,statistics,uuid,secrets
Blocked Modules (always restricted):
os,sys,subprocess,multiprocessing,threadingsocket,urllib,requests,http,ftplib,smtplibimportlib,eval,exec,compile
β
Import restrictions: Dangerous modules are blocked
β
Resource limits: CPU, memory, and process limits enforced
β
Filesystem isolation: Code runs in temporary directories
β
Network blocking: Optional socket-level blocking
β
Timeout enforcement: Hard timeout prevents infinite loops
β
AST validation: Compile-time code analysis
# Install dev dependencies
pip install -e ".[dev]"
# Run all tests
pytest
# Run with coverage
pytest --cov=src --cov-report=html
# Run specific test file
pytest tests/test_sandbox_executor.pySee tests/README.md for detailed testing documentation.
The sandbox is compatible with:
- AWS Fargate: Deploy as ECS task
- Azure Container Apps: Deploy as container app
- Azure Kubernetes Service with Kata runtime: For more isolation, learn more at https://learn.microsoft.com/en-us/azure/aks/use-pod-sandboxing
- Google Cloud Run: Deploy as Cloud Run service
- Heroku: Deploy as Docker container
- DigitalOcean App Platform: Deploy as Docker app
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- GitHub Issues: Report bugs or request features
- Examples: Check the examples/ directory
If you find this project useful, please give it a star! β
Made with β€οΈ for the Python & AI community