使用 sandbox.getHost(port) 可以擷取 Sandbox 指定連接埠的公網訪問地址。適合訪問 Sandbox 內啟動的 HTTP 服務、程式開發伺服器或調試服務。
啟動服務並訪問
TypeScript 樣本:
import { Sandbox } from "e2b";
const sandbox = await Sandbox.create("code-interpreter-v1", {
apiKey: process.env.E2B_API_KEY,
apiUrl: process.env.E2B_API_URL,
domain: process.env.E2B_DOMAIN,
});
try {
const process = await sandbox.commands.run("python3 -m http.server 8000", {
background: true,
});
const host = sandbox.getHost(8000);
const url = `https://${host}`;
console.log(url);
const response = await fetch(url);
console.log(await response.text());
await process.kill();
} finally {
await sandbox.kill();
}Python 樣本:
import os
import urllib.request
import time
from e2b import Sandbox
sandbox = Sandbox.create(
template="code-interpreter-v1",
api_key=os.environ["E2B_API_KEY"],
api_url=os.environ["E2B_API_URL"],
domain=os.environ["E2B_DOMAIN"],
)
try:
process = sandbox.commands.run(
"python3 -m http.server 8000",
background=True,
)
time.sleep(2) # Wait for http.server to start
host = sandbox.get_host(8000)
url = f"https://{host}"
print(url)
with urllib.request.urlopen(url, timeout=10) as response:
print(response.read().decode())
process.kill()
finally:
sandbox.kill()注意事項
調用
getHost(port)前,需要確保 Sandbox 內已有服務監聽對應連接埠。getHost(port)返回的是 host,訪問時通常需要拼接https://。後台服務不會自動結束,任務完成後要主動終止進程或終止 Sandbox。
不要在未鑒權的連接埠服務中暴露敏感性資料、內部調試介面或長期有效憑證。