Exécution de code sandboxé avec E2B

VérifiéSûr

Plateforme cloud E2B pour exécuter du code généré par IA dans des sandboxes Linux isolées avec filesystem, gestionnaires de paquets et accès internet.

Spar Skills Guide Bot
Data & IAIntermédiaire
17/11/2026
Claude CodeCursorWindsurfCopilotCodex
#sandbox#code-execution#ai-agents#cloud#e2b

Recommandé pour

Synthèse automatique

Ce skill explique comment utiliser E2B pour exécuter du code Python ou JavaScript généré par une IA dans des sandboxes Linux cloud isolées, avec gestion des fichiers, installation de paquets et sorties riches.

Points forts

  • Couvre le cycle complet : installation, authentification via E2B_API_KEY, création de sandbox, exécution de code et arrêt.
  • Montre des cas concrets utiles aux agents : pip install, lecture/écriture de fichiers, graphiques matplotlib renvoyés en base64 et prolongation du timeout.
  • Fournit des exemples en TypeScript et une variante JavaScript avec fetch réseau.
  • Rappelle de ne pas coder en dur la clé API et de tuer explicitement la sandbox.

Limites

  • Dépend d'un service cloud tiers et d'une clé API, donc inadapté aux environnements hors ligne ou strictement on-premise.
  • Ne détaille pas réellement le branchement à LangChain ou CrewAI malgré la description, ni les stratégies de retry et de gestion d'erreurs.
  • Les exemples sont surtout TypeScript et n'abordent pas la persistance ou le nettoyage avancé des ressources.
Quand l'utiliser

À utiliser lorsqu'un agent doit exécuter du code non fiable, analyser des données ou produire des graphiques sans exposer la machine hôte.

Quand l'éviter

À éviter si le code ou les données ne peuvent pas quitter votre infrastructure, ou si un simple conteneur local suffit.

Analyse de sécurité

Sûr
Score qualité88/100

The skill is documentation for the E2B sandboxed code-execution SDK. It contains no destructive host commands, no obfuscated payloads, and no exfiltration of credentials; it explicitly advises keeping E2B_API_KEY in environment variables, never hardcoding it or shipping it in client bundles, and warns that sandbox outbound internet access is an attack surface. Code execution occurs in ephemeral remote VMs, which is the stated and legitimate purpose. The only "powerful" operations (pip install, arbitrary Python/JS in a sandbox) are scoped to the isolated environment, so there is no meaningful risk to a host machine from listing the skill.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Analyze a CSV in a sandbox
Use E2B to create a sandbox, upload quarterly-revenue.csv, run a pandas analysis, return the matplotlib chart as a base64 PNG, and then kill the sandbox.
Add sandboxed Python to an agent
Wire E2B code execution into my LangChain agent so it can install packages and run generated Python in an isolated sandbox, with a 10-minute timeout and cleanup.
Run JavaScript with network access
Run a JavaScript snippet in an E2B sandbox that fetches the GitHub repo stats and prints the star count.

name: e2b description: >- E2B is a cloud platform that gives AI agents secure, isolated sandboxes — ephemeral Linux VMs with a filesystem, package managers, and internet access — to run AI-generated code safely. Use when a user wants an agent to execute Python or JavaScript, install packages, read/write files, or run a long process without risking the host machine, or wants to wire code execution into a LangChain, CrewAI, or custom agent loop. license: Apache-2.0 compatibility: "Node.js 20.18+ or Python 3.8+, an E2B API key" metadata: author: terminal-skills version: "1.1.0" category: data-ai tags: "sandbox, code-execution, ai-agents, cloud, e2b" repository: https://github.com/e2b-dev/E2B

E2B — Sandboxed Code Execution for AI

Overview

E2B runs AI-generated code inside short-lived, isolated cloud sandboxes rather than on the host machine. Each sandbox is a Linux VM created from a snapshot, with its own filesystem, package managers, and outbound internet access; it is destroyed when killed or when it times out. The @e2b/code-interpreter (JS/TS) and e2b-code-interpreter (Python) packages add a runCode method on top of the base E2B SDK that is purpose-built for data/AI workloads: it returns rich results (stdout/stderr, tracebacks, and rendered outputs like matplotlib charts as base64 images) instead of just an exit code.

Instructions

Install and authenticate

npm install @e2b/code-interpreter dotenv

Set E2B_API_KEY (from the E2B dashboard) as an environment variable — never hardcode it in source.

Run code in a sandbox

import { Sandbox } from "@e2b/code-interpreter";

const sandbox = await Sandbox.create(); // default timeout: 5 minutes

const result = await sandbox.runCode(`
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"x": range(10), "y": [i**2 for i in range(10)]})
plt.figure(figsize=(8, 5))
plt.plot(df.x, df.y)
plt.title("Quadratic Growth")
plt.savefig("/tmp/chart.png")
print(f"Data points: {len(df)}")
`);

console.log(result.logs.stdout); // ["Data points: 10"]
console.log(result.results);     // [{ type: "png", data: "base64..." }]

await sandbox.kill();

Install packages, read/write files, extend the timeout

await sandbox.runCode("!pip install scikit-learn");
await sandbox.runCode(`
from sklearn.linear_model import LinearRegression
model = LinearRegression().fit([[1], [2], [3]], [1, 2, 3])
print(model.predict([[4]]))
`);

await sandbox.files.write("/tmp/sales.csv", csvContent);
const preview = await sandbox.runCode(
  "import pandas as pd; print(pd.read_csv('/tmp/sales.csv').head())"
);
const chartBytes = await sandbox.files.read("/tmp/chart.png");

// Default lifetime is 5 minutes; extend it explicitly for longer jobs
// (max 1 hour on the Hobby plan, 24 hours on Pro).
await sandbox.setTimeout(10 * 60_000);

Run JavaScript instead of Python

const jsResult = await sandbox.runCode(
  `
  const response = await fetch('https://api.github.com/repos/e2b-dev/e2b');
  const data = await response.json();
  console.log(data.stargazers_count);
  `,
  { language: "javascript" }
);

Examples

Example 1: "Let an agent analyze a CSV and return a chart"

import { Sandbox } from "@e2b/code-interpreter";
import { readFileSync } from "fs";

const sandbox = await Sandbox.create();
const csv = readFileSync("quarterly-revenue.csv");
await sandbox.files.write("/tmp/quarterly-revenue.csv", csv);

const analysis = await sandbox.runCode(`
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("/tmp/quarterly-revenue.csv")
plt.bar(df["quarter"], df["revenue"])
plt.savefig("/tmp/revenue.png")
print(df.describe())
`);

console.log(analysis.logs.stdout.join("\n"));
const [chart] = analysis.results.filter((r) => r.png);
await sandbox.kill();

The agent writes and runs arbitrary pandas/matplotlib code; analysis.results carries the chart back as a base64 PNG with no file download step needed.

Example 2: "Give a LangChain agent a code-execution tool"

import { Sandbox } from "@e2b/code-interpreter";
import { tool } from "@langchain/core/tools";
import { z } from "zod";

const sandbox = await Sandbox.create({ timeoutMs: 10 * 60_000 });

const runPython = tool(
  async ({ code }) => {
    const execution = await sandbox.runCode(code);
    return execution.logs.stdout.join("\n") || execution.error?.value || "";
  },
  {
    name: "run_python",
    description: "Executes Python code in a sandboxed environment and returns stdout.",
    schema: z.object({ code: z.string() }),
  }
);

The agent calls run_python whenever it needs to compute something instead of guessing; the sandbox's isolation means a wrong or malicious snippet can't touch the host.

Guidelines

  • A sandbox self-destructs after its timeout (default 5 minutes); call sandbox.setTimeout() before it expires for long-running jobs, and always kill() sandboxes you're done with rather than relying on the timeout alone, since idle sandboxes still bill for uptime.
  • Never bake the E2B_API_KEY into committed code or client-side bundles — the key can create sandboxes and billed compute on your account.
  • Build a custom sandbox template (prebaked with your packages) when cold-installing dependencies on every run is too slow; the base template includes NumPy, Pandas, and Matplotlib but not arbitrary packages.
  • Sandboxes have outbound internet access by default — treat that as an attack surface if you're running untrusted, user-submitted code, not just AI-generated code you've reviewed.
  • Use @e2b/code-interpreter's runCode for data/analysis workloads that need rich results (charts, tracebacks); use the base e2b SDK's shell commands (sandbox.commands.exec) for general-purpose process execution that doesn't need that return shape.

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/sandboxed-code-execution-with-e2b-mwirmdw9/download' --output '.skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9/SKILL.md.part' && mv '.skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9/SKILL.md.part' '.skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Environnement déclaré par l’auteur : Node.js 20.18+ or Python 3.8+, an E2B API key

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9/SKILL.md' && test -s '.skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/e2b' && cp -R '.skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9' '.claude/skills/e2b'

Cursor
test -f '.skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9/SKILL.md' && test -s '.skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/e2b' && cp -R '.skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9' '.cursor/skills/e2b'

Codex
test -f '.skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9/SKILL.md' && test -s '.skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/e2b' && cp -R '.skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9' '.agents/skills/e2b'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9'

openskills read 'sandboxed-code-execution-with-e2b-mwirmdw9'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/sandboxed-code-execution-with-e2b-mwirmdw9/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires