Execute commands safely with configurable shell control across different backends
Sandbox backends provide isolated command execution environments with explicit shell control to prevent injection attacks while enabling shell features when needed.
from praisonai.sandbox import SubprocessSandbox# Local development with subprocesssandbox = SubprocessSandbox()result = await sandbox.run_command("python test.py")
from praisonai.sandbox import DockerSandboxsandbox = DockerSandbox()# Process user data safelyasync def process_file(filename): # Safe: no shell injection possible result = await sandbox.run_command([ "python", "process.py", "--input", filename ], shell=False) return result.stdout# Process with shell features when controlledasync def count_errors(log_file): import shlex # Trusted input, need shell features result = await sandbox.run_command( f"grep 'ERROR' {shlex.quote(log_file)} | wc -l", shell=True ) return int(result.stdout.strip())
Model-generated commands or user input should never use shell=True to prevent injection attacks. The default shell=False provides automatic protection.
# ✅ Safe with any user inputuser_script = request.get("script")result = await sandbox.run_command(f"python {user_script}", shell=False)# ❌ Vulnerable to injectionresult = await sandbox.run_command(f"python {user_script}", shell=True)
Quote arguments when building shell commands
If you must use shell=True, quote all dynamic arguments with shlex.quote():
import shlexfilename = user_input # Could contain special characterscommand = f"process.py --file {shlex.quote(filename)}"result = await sandbox.run_command(command, shell=True)
Prefer list form for complex commands
Using argument lists avoids shell parsing entirely: