> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.xapi.to/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.xapi.to/_mcp/server.

# 执行 Shell 命令

POST https://sandbox.xapi.to/v1/sandboxes/{id}/commands
Content-Type: application/json

需要实例为 RUNNING，且 offering 声明 exec 能力。前台命令的非零 exitCode 是远端命令失败，
不等同于 HTTP 失败。需要启动 Web 服务等长驻进程时可传 background=true，但必须先确认
offering.capabilities.backgroundExec=true；此时响应表示后台会话已接受，不代表进程已经监听端口。


Reference: https://docs.xapi.to/sandbox/api-reference/execution/execute-command

## Authentication

- `XAPI-Key` header (required) — 在 xAPI Console 创建的 API Key。只会发送给 *.xapi.to。

## Servers

- `https://sandbox.xapi.to` (Production, default)
- `https://sandbox.test.xapi.to` (Test)

## Request

### Path parameters

- `id` (string, required) — xAPI Sandbox 实例 UUID。

### Body (application/json)

This endpoint expects a CommandRequest.

- `command` (string, required) — 传给供应商 Shell 的完整命令。不要把 XAPI-Key 或其他密钥拼进命令或输出。
- `cwd` (string, optional) — 命令工作目录；省略时使用 offering/适配器的默认工作区。
- `env` (map from string to string, optional) — 仅对本次命令生效的环境变量映射；敏感值可能进入供应商进程环境，应谨慎使用。
- `timeoutSeconds` (integer, optional, default: 60) — 远端命令最长执行秒数；超时会停止等待并记录失败，不会自动销毁整个 Sandbox。
- `background` (boolean, optional, default: false) — true=在供应商托管的异步会话中启动命令并立即返回，适合监听端口的 Web 服务； 仅当 offering.capabilities.backgroundExec=true 时可用。不要用 shell 的 nohup/& 替代： 部分供应商会在前台 exec 请求结束时回收该命令会话及其子进程。

## Response

### 201

命令结果

- `exitCode` (integer, required) — 前台命令的远端进程退出码。background=true 时 0 仅表示后台会话已接受，不能证明进程已就绪或最终成功。
- `stdout` (string, required) — 命令标准输出。可能为空，也可能因输出上限被截断。
- `stderr` (string, required) — 命令标准错误。非空不一定失败，最终同时判断 exitCode。
- `truncated` (boolean, optional) — stdout 或 stderr 是否超过响应上限而被截断；为 true 时完整制品应写入文件再下载。
- `background` (CommandResultBackground, optional) — 仅 background=true 时返回的供应商托管会话标识；用于审计和问题定位，不是公开访问凭证。

## Errors

### 400 Bad Request Error

请求参数无效或没有兼容规格

- `statusCode` (integer, optional) — HTTP 状态码的数值形式，例如 400、401、402、404、409 或 429。
- `message` (ErrorMessage, optional) — 面向调用方的错误原因；校验失败时可能是多条消息数组。
- `error` (string, optional) — HTTP 错误类别，例如 Bad Request、Unauthorized 或 Conflict。

### 404 Not Found Error

实例或资源不存在，或者不属于当前账户

- `statusCode` (integer, optional) — HTTP 状态码的数值形式，例如 400、401、402、404、409 或 429。
- `message` (ErrorMessage, optional) — 面向调用方的错误原因；校验失败时可能是多条消息数组。
- `error` (string, optional) — HTTP 错误类别，例如 Bad Request、Unauthorized 或 Conflict。

### 409 Conflict Error

实例状态不允许当前操作，或已有状态变更正在执行

- `statusCode` (integer, optional) — HTTP 状态码的数值形式，例如 400、401、402、404、409 或 429。
- `message` (ErrorMessage, optional) — 面向调用方的错误原因；校验失败时可能是多条消息数组。
- `error` (string, optional) — HTTP 错误类别，例如 Bad Request、Unauthorized 或 Conflict。

## Types

### CommandResultBackground

仅 background=true 时返回的供应商托管会话标识；用于审计和问题定位，不是公开访问凭证。

- `sessionId` (string, required) — xAPI 在供应商内创建并保留到 Sandbox 销毁的命令会话 ID。
- `commandId` (string, required) — 供应商返回的异步命令 ID。

### ErrorMessage

面向调用方的错误原因；校验失败时可能是多条消息数组。

- string
- list of string

## Examples

### 验证 Shell 输出

**Request**

```json
{
  "command": "python3 -c \"print('XAPI_SANDBOX_OK=42')\"",
  "timeoutSeconds": 60
}
```

**Response**

```json
{
  "exitCode": 0,
  "stdout": "XAPI_SANDBOX_OK=42\n",
  "stderr": "",
  "truncated": false
}
```

**SDK Code**

```python 验证 Shell 输出
import requests

url = "https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands"

payload = {
    "command": "python3 -c \"print('XAPI_SANDBOX_OK=42')\"",
    "timeoutSeconds": 60
}
headers = {
    "XAPI-Key": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 验证 Shell 输出
const url = 'https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands';
const options = {
  method: 'POST',
  headers: {'XAPI-Key': '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"command":"python3 -c \"print(\'XAPI_SANDBOX_OK=42\')\"","timeoutSeconds":60}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go 验证 Shell 输出
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands"

	payload := strings.NewReader("{\n  \"command\": \"python3 -c \\\"print('XAPI_SANDBOX_OK=42')\\\"\",\n  \"timeoutSeconds\": 60\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("XAPI-Key", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby 验证 Shell 输出
require 'uri'
require 'net/http'

url = URI("https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["XAPI-Key"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"command\": \"python3 -c \\\"print('XAPI_SANDBOX_OK=42')\\\"\",\n  \"timeoutSeconds\": 60\n}"

response = http.request(request)
puts response.read_body
```

```java 验证 Shell 输出
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands")
  .header("XAPI-Key", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"command\": \"python3 -c \\\"print('XAPI_SANDBOX_OK=42')\\\"\",\n  \"timeoutSeconds\": 60\n}")
  .asString();
```

```php 验证 Shell 输出
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands', [
  'body' => '{
  "command": "python3 -c \\"print(\'XAPI_SANDBOX_OK=42\')\\"",
  "timeoutSeconds": 60
}',
  'headers' => [
    'Content-Type' => 'application/json',
    'XAPI-Key' => '<apiKey>',
  ],
]);

echo $response->getBody();
```

```csharp 验证 Shell 输出
using RestSharp;

var client = new RestClient("https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands");
var request = new RestRequest(Method.POST);
request.AddHeader("XAPI-Key", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"command\": \"python3 -c \\\"print('XAPI_SANDBOX_OK=42')\\\"\",\n  \"timeoutSeconds\": 60\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 验证 Shell 输出
import Foundation

let headers = [
  "XAPI-Key": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [
  "command": "python3 -c \"print('XAPI_SANDBOX_OK=42')\"",
  "timeoutSeconds": 60
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### 启动后台 Web 服务

**Request**

```json
{
  "command": "python3 -m http.server 25319 --bind 0.0.0.0",
  "background": true
}
```

**Response**

```json
{
  "exitCode": 0,
  "stdout": "",
  "stderr": "",
  "truncated": false,
  "background": {
    "sessionId": "xapi-aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee",
    "commandId": "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"
  }
}
```

**SDK Code**

```python 启动后台 Web 服务
import requests

url = "https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands"

payload = {
    "command": "python3 -m http.server 25319 --bind 0.0.0.0",
    "background": True
}
headers = {
    "XAPI-Key": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 启动后台 Web 服务
const url = 'https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands';
const options = {
  method: 'POST',
  headers: {'XAPI-Key': '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"command":"python3 -m http.server 25319 --bind 0.0.0.0","background":true}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go 启动后台 Web 服务
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands"

	payload := strings.NewReader("{\n  \"command\": \"python3 -m http.server 25319 --bind 0.0.0.0\",\n  \"background\": true\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("XAPI-Key", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby 启动后台 Web 服务
require 'uri'
require 'net/http'

url = URI("https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["XAPI-Key"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"command\": \"python3 -m http.server 25319 --bind 0.0.0.0\",\n  \"background\": true\n}"

response = http.request(request)
puts response.read_body
```

```java 启动后台 Web 服务
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands")
  .header("XAPI-Key", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"command\": \"python3 -m http.server 25319 --bind 0.0.0.0\",\n  \"background\": true\n}")
  .asString();
```

```php 启动后台 Web 服务
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands', [
  'body' => '{
  "command": "python3 -m http.server 25319 --bind 0.0.0.0",
  "background": true
}',
  'headers' => [
    'Content-Type' => 'application/json',
    'XAPI-Key' => '<apiKey>',
  ],
]);

echo $response->getBody();
```

```csharp 启动后台 Web 服务
using RestSharp;

var client = new RestClient("https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands");
var request = new RestRequest(Method.POST);
request.AddHeader("XAPI-Key", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"command\": \"python3 -m http.server 25319 --bind 0.0.0.0\",\n  \"background\": true\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 启动后台 Web 服务
import Foundation

let headers = [
  "XAPI-Key": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [
  "command": "python3 -m http.server 25319 --bind 0.0.0.0",
  "background": true
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/commands")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```