更新网络配置

更新时间:
复制 MD 格式

沙箱运行期间可调用 updateNetwork(Node.js)或 update_network(Python)同时更新出网规则和凭证注入规则,无需重建沙箱。

何时需要更新网络配置

如果只需调整运行中沙箱的出网白名单,也需在同一更新请求中保留所需的凭证规则。反过来,轮换凭证时也需重新提交要保留的出网规则。参见配置出网流量控制和凭证注入。

操作步骤

updateNetwork 使用全量替换语义,不会与现有配置合并。每次调用都必须提交最终需要保留的 allowInternetAccess、allowOut、denyOut 和 rules:

  • 更新凭证注入规则时,需要同时提交要保留的出网规则。

  • 更新出网规则时,需要同时提交要保留的凭证注入规则。

  • 未提交的凭证注入规则和出网规则不会自动保留;省略 rules、传入 null 或 {} 会清空已有凭证注入规则。M2M options 与用户委托 OAuth options 两张参数表不在此列,按独立更新规则处理,见 OAuth 配置更新规则。

Python 示例使用 Python 3.10 或更高版本及 E2B Python SDK 2.31.0。可运行 python3 -m pip install e2b==2.31.0 安装。

以下示例同时更新出网规则和 API Key 注入规则:

Node.js

await sandbox.updateNetwork({
  allowInternetAccess: true,
  allowOut: ["api.example.com"],
  denyOut: ["0.0.0.0/0"],
  rules: {
    "api.example.com": [{
      transform: {
        headers: {
          Authorization: "Bearer ${fc.sandbox.identity.apiKey:new-model-provider}",
        },
      },
    }],
  },
});

Python

sandbox.update_network({
    "allow_internet_access": True,
    "allow_out": ["api.example.com"],
    "deny_out": ["0.0.0.0/0"],
    "rules": {
        "api.example.com": [{
            "transform": {
                "headers": {
                    "Authorization":
                        "Bearer ${fc.sandbox.identity.apiKey:new-model-provider}"
                }
            }
        }]
    },
})

出网规则的配置方法参见配置出网流量控制,凭证规则的配置方法参见凭证注入。

运行时更新出网配置

创建后可以用 updateNetwork(Node.js)/ update_network(Python)在不重建沙箱的情况下调整出网规则。以下示例新建一个未配置凭证注入的沙箱,依次屏蔽单个 IP、切换到域名白名单和关闭出网。普通网络配置为全量替换,未提交的字段会被清空,每次调用都需提交完整的 allowInternetAccess、allowOut、denyOut 和 rules;已有凭证注入规则的沙箱,还需一并提交要保留的规则。

Node.js

import { Sandbox } from "e2b";

const sandbox = await Sandbox.create({
  apiKey: process.env.E2B_API_KEY,
  apiUrl: process.env.E2B_API_URL,
  domain: process.env.E2B_DOMAIN,
});
console.log(`[create] 沙箱已创建: ${sandbox.sandboxId}`);

try {
  // 收紧:屏蔽单个 IP
  await sandbox.updateNetwork({
    allowInternetAccess: true,
    allowOut: [],
    denyOut: ["8.8.8.8"],
    rules: {},
  });
  console.log("[update] 已屏蔽 8.8.8.8");

  // 替换为纯白名单
  await sandbox.updateNetwork({
    allowInternetAccess: true,
    allowOut: ["api.example.com"],
    denyOut: ({ allTraffic }) => [allTraffic],
    rules: {},
  });
  console.log("[update] 已切换为白名单:仅放行 api.example.com");

  // 直接切换出网总开关
  await sandbox.updateNetwork({
    allowInternetAccess: false,
    allowOut: [],
    denyOut: ["0.0.0.0/0"],
    rules: {},
  });
  console.log("[update] 已关闭出网总开关");
} finally {
  // 执行完成后主动销毁沙箱,避免残留占用与计费
  await sandbox.kill();
  console.log("[cleanup] 沙箱已销毁");
}

Python

import os

from e2b import Sandbox

sandbox = Sandbox.create(
    api_key=os.environ["E2B_API_KEY"],
    api_url=os.environ["E2B_API_URL"],
    domain=os.environ["E2B_DOMAIN"],
)
print(f"[create] 沙箱已创建: {sandbox.sandbox_id}")

try:
    # 收紧:屏蔽单个 IP
    sandbox.update_network({
        "allow_internet_access": True,
        "allow_out": [],
        "deny_out": ["8.8.8.8"],
        "rules": {},
    })
    print("[update] 已屏蔽 8.8.8.8")

    # 替换为纯白名单
    sandbox.update_network({
        "allow_internet_access": True,
        "allow_out": ["api.example.com"],
        "deny_out": lambda ctx: [ctx.all_traffic],
        "rules": {},
    })
    print("[update] 已切换为白名单:仅放行 api.example.com")

    # 直接切换出网总开关
    sandbox.update_network({
        "allow_internet_access": False,
        "allow_out": [],
        "deny_out": ["0.0.0.0/0"],
        "rules": {},
    })
    print("[update] 已关闭出网总开关")
finally:
    # 执行完成后主动销毁沙箱,避免残留占用与计费
    sandbox.kill()
    print("[cleanup] 沙箱已销毁")

注意:

  • updateNetwork 是全量替换,不与已有规则合并;传入空对象 updateNetwork({}) 会清空创建时设置的全部 allow / deny 规则。

  • 出网相关的 allowInternetAccess / allowOut / denyOut / rules 可更新(创建沙箱时该字段的配置路径为 network.rules)。allowPublicTraffic 与 maskRequestHost 属于创建时锁定参数,创建后不可修改。rules 的具体配置方式,请参见凭证注入。

使用说明

生效规则

  • 只有运行中的沙箱支持更新;暂停的沙箱需要先恢复。

  • 请求参数未通过校验时,原配置继续生效。服务端报错或请求超时后,运行中的沙箱可能已应用新策略。请先查询已保存的网络配置,再从当前沙箱发起请求,验证目标是否按预期放行或拒绝。需要重试时,请重新提交完整的目标配置。

  • 网络配置在暂停(Pause)与恢复(Resume)后保留,并在恢复后的实例上重新应用。

OAuth 配置更新规则

M2M(Machine to Machine)OAuth 和用户委托 OAuth 的配置各自独立更新,与普通网络配置的全量替换不同:

  • M2M options 按 Provider 名称组成一张参数表,整表处理:省略该字段时保留原表,提交时整体替换该 M2M Provider 表,传入 {} 时清空该表的会话级参数。因此要保留其他 Provider 时需一起提交,同一 Provider 需保留的 scopes 和 customParameters 也要一并提交。具体见 M2M OAuth 注入。

  • 用户委托 OAuth 的 JWT(JSON Web Token)与 UserId 二选一,都省略则保留当前用户身份,提交其中一个时替换当前身份并清除另一个。每次提交 JWT 都会重新验证,即使提交的是相同的 JWT。允许切换为另一用户身份,新 JWT 仍须验证通过,所需的 OAuth 授权仍须完成。具体见用户委托 OAuth 注入。

使用限制

  • allowPublicTraffic 和 maskRequestHost 只能在创建沙箱时设置。

  • 托管 STS(Security Token Service,安全令牌服务)使用的 Workload Identity、Role Policy 和重签域名不能通过 updateNetwork 修改;需要更换时,请创建新沙箱。

更多操作

查询当前配置

getInfo 或 GET /sandboxes/{id} 会返回已保存的网络配置,可用于构造下一次完整的更新请求。

自带凭证方式会明文返回凭证注入规则中的真实凭证值(value),不要把查询响应写入普通日志、工单或前端上报。Agent Identity 托管方式只返回引用表达式,不返回真实凭证。