This service allows secure execution of arbitrary Python scripts in an isolated environment using Flask and nsjail.
- Secure script execution using Linux namespaces (nsjail)
- JSON API for script submission and result retrieval
- Support for popular libraries (numpy, pandas)
- Docker (for containerized deployment)
- nsjail (installed automatically in Docker image)
./test_service.shBuild the image (multi-stage, minimal final image):
docker build -t python-execution-service .Run the service (with nsjail sandboxing):
docker run --privileged -p 8080:8080 --rm -e DEBUG=1 python-execution-serviceSecurity Note: The --privileged flag is required for nsjail to function fully. For production, review nsjail and Docker security documentation to minimize risk.
The container runs as a non-root user (sandboxuser) for improved security.
-
Install nsjail (follow instructions at https://github.com/google/nsjail)
-
Install dependencies:
pip install -r requirements.txt numpy pandas
-
Set
PYTHON_PATHto point to your local Python interpreter if necessary:export PYTHON_PATH=$(which python)
⚠️ Note: If you are using a virtual environment, make sure it is activated before running the above command. -
Run the service:
DEBUG=1 python -m src.main
curl -X GET http://localhost:8080/healthcurl -X POST http://localhost:8080/execute \
-H "Content-Type: application/json" \
-d '{
"script": "def main():\n import numpy as np\n arr = np.array([1, 2, 3, 4, 5])\n print(\"This will not be in the result\")\n return {\"sum\": int(np.sum(arr)), \"mean\": float(np.mean(arr))}"
}'Example response:
{
"result": {
"sum": 15,
"mean": 3.0
},
"stdout": "This will not be in the result\n"
}