> For the complete documentation index, see [llms.txt](https://docs.verge.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.verge.io/learn-the-platform/zh/mo-kuai-8-kai-fa-yu-devops/01-api-cli.md).

# REST API 与 CLI 工具

你在 VergeOS UI 中执行的每个操作都直接映射为一次 REST API 调用。这 **API 优先设计** 意味着你在仪表板中能点击的任何内容——创建虚拟机、配置网络、管理租户——都可以通过 HTTP 端点实现自动化。本节介绍用于程序化访问的三个主要接口： **REST API** 本身， **yb-api 辅助脚本** 用于本机自动化，以及 **vrg CLI** 用于远程管理。

## REST API 概览

VergeOS API 遵循标准 REST 约定，使用 JSON 负载，支持平台中每个资源的完整生命周期。

### HTTP 方法

| 方法         | 用途        | 示例                            |
| ---------- | --------- | ----------------------------- |
| **GET**    | 检索资源      | `GET /api/v4/vms?fields=most` |
| **POST**   | 创建资源或触发操作 | `POST /api/v4/vms`            |
| **PUT**    | 更新现有资源    | `PUT /api/v4/vms/36`          |
| **DELETE** | 移除资源      | `DELETE /api/v4/vms/36`       |

### 查询参数

每个 GET 请求都支持 OData 风格的过滤和字段选择：

* **`字段`** — 指定要返回的字段（例如： `fields=name,$key,ram` 或 `fields=most` 用于所有常用字段）
* **`filter`** — OData 风格的过滤表达式（例如： `filter=is_snapshot eq false`)
* **`sort`** — 按字段对结果排序（例如： `sort=name`)
* **`limit`** / **`offset`** — 用于大型结果集的分页控制

### 数据格式

所有 API 响应都以 **JSON 格式**返回。POST 和 PUT 操作的请求体也必须是 JSON，并带有 `Content-Type: application/json` 头。

### 速率限制

该 API 每个 API 密钥最多支持 **每小时 1,000 个请求** 。对于高频自动化，请尽可能进行批量操作，并实现带指数退避的重试逻辑。

## 身份验证

VergeOS 支持两种身份验证方法——Basic HTTP 身份验证和基于令牌的身份验证——分别适用于不同的使用场景。长期有效的 API 密钥是令牌方法的一种变体，它以 Bearer token 而不是会话 token 的形式提供：

### 1. Basic HTTP 身份验证

最简单的方法——在每次请求中直接传递凭据。所有 API 流量都需要 HTTPS。

```bash
curl -X GET "https://vergeos.example.com/api/v4/vms?fields=most" \
  --basic --user "admin:password" \
  -H "Accept: application/json"
```

### 2. 基于令牌的身份验证（会话令牌）

通过将凭据 POST 到 `/sys/tokens`来请求会话令牌。之后在后续请求中通过 `x-yottabyte-token` 请求头使用返回的令牌：

```bash
# 第 1 步：获取令牌
curl --basic \
  --data-ascii '{"login": "admin", "password": "secret"}' \
  --request "POST" \
  --header "Content-Type: application/json" \
  "https://vergeos.example.com/api/sys/tokens"

# 响应包含令牌密钥：
# {"location":"/sys/tokens/3a334...","$key":"3a334..."}

# 第 2 步：在后续请求中使用令牌
curl -X GET "https://vergeos.example.com/api/v4/vms?fields=most" \
  -H "x-yottabyte-token: 3a334..." \
  -H "Accept: application/json"

# 第 3 步：完成后注销
curl -X DELETE "https://vergeos.example.com/api/sys/tokens/3a334..."
```

#### Bearer-Token 变体：长期有效的 API 密钥

对于生产环境自动化，请通过 **系统 → 用户 → \[用户] → API 密钥**创建持久化 API 密钥。这些密钥是令牌身份验证的 Bearer-token 变体——它们作为 Bearer token 使用，并保持有效，直到过期或被删除：

```bash
curl -X GET "https://vergeos.example.com/api/v4/vms?fields=most" \
  -H "Authorization: Bearer your-api-key-string" \
  -H "Content-Type: application/json"
```

API 密钥支持 **IP 允许/拒绝列表** 用于安全控制以及可配置的 **过期日期**。请将它们存储在环境变量中，而不是硬编码：

```bash
export VERGEOS_API_KEY="your-api-key-string"
curl -X GET "https://vergeos.example.com/api/v4/system" \
  -H "Authorization: Bearer ${VERGEOS_API_KEY}"
```

{% hint style="warning" %}
API 密钥在创建时只显示一次。如果丢失，必须删除该密钥并创建新的。
{% endhint %}

## API Explorer（Swagger）

VergeOS 包含一个内置的 **Swagger 文档页面** ，它由运行中的系统动态生成，显示所有可用表和操作。

**要访问它：**

1. 登录 VergeOS UI
2. 导航至 **系统 → API 文档**
3. 浏览可用端点，查看模式，并直接测试 API 调用

Swagger 界面允许你在浏览器中执行 API 调用，并查看生成的 `curl` 命令、响应正文和请求头——这使它成为编写自动化脚本的绝佳工具。

## 关键 API 端点

API 将资源组织为表。以下是最常用的端点：

| 端点                            | 用途            |
| ----------------------------- | ------------- |
| `/api/v4/vms`                 | 虚拟机 CRUD 操作   |
| `/api/v4/vm_actions`          | 虚拟机电源操作、克隆、快照 |
| `/api/v4/machine_drives`      | 附加/管理虚拟机存储磁盘  |
| `/api/v4/machine_nics`        | 配置虚拟机网络接口     |
| `/api/v4/machine_devices`     | GPU/PCI 设备直通  |
| `/api/v4/machine_status/{id}` | 运行时电源状态和状态    |
| `/api/v4/vnets`               | 虚拟网络管理        |
| `/api/v4/vnet_rules`          | 防火墙和 NAT 规则   |
| `/api/v4/tenants`             | 租户（VDC）管理     |
| `/api/v4/nodes`               | 物理节点信息        |
| `/api/v4/clusters`            | 集群配置          |
| `/api/sys/tokens`             | 会话令牌管理        |

### 模式自省

附加 `/$table` 到任何端点，以检索其完整数据库模式，包括所有可用字段和类型：

```bash
# 获取 VM 表模式
curl -X GET "https://vergeos.example.com/api/v4/vms/\$table" \
  -H "Authorization: Bearer ${VERGEOS_API_KEY}"
```

## 虚拟机生命周期 API 演示

最常见的自动化工作流是通过 API 配置完整的虚拟机。这个四步流程与 UI 在后台执行的操作一致：

```mermaid
graph LR
    A["1. 创建虚拟机"] --> B["2. 添加磁盘"]
    B --> C["3. 添加网卡"]
    C --> D["4. 开机"]
    style A fill:#e8f5e9,stroke:#2e7d32
    style B fill:#e3f2fd,stroke:#1565c0
    style C fill:#fff3e0,stroke:#ef6c00
    style D fill:#fce4ec,stroke:#c62828
```

### 第 1 步：创建虚拟机

```bash
curl -X POST "https://vergeos.example.com/api/v4/vms" \
  -H "Authorization: Bearer ${VERGEOS_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "web-server-01",
    "description": "生产 Web 服务器",
    "machine_type": "pc-q35-9.0",
    "cpu_cores": 4,
    "cpu_type": "Cascadelake-Server",
    "ram": 8192,
    "os_family": "linux",
    "boot_order": "cd",
    "uefi": true,
    "allow_hotplug": true
  }'

# 响应：{"location":"/v4/vms/42","$key":"42"}
```

### 第 2 步：添加存储磁盘

```bash
curl -X POST "https://vergeos.example.com/api/v4/machine_drives" \
  -H "Authorization: Bearer ${VERGEOS_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "machine": 42,
    "name": "boot-disk",
    "media": "disk",
    "interface": "virtio-scsi",
    "disksize": 107374182400,
    "preferred_tier": "1"
  }'
```

### 第 3 步：添加网络接口

```bash
curl -X POST "https://vergeos.example.com/api/v4/machine_nics" \
  -H "Authorization: Bearer ${VERGEOS_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "machine": 42,
    "vnet": 6,
    "interface": "virtio"
  }'
```

### 第 4 步：开机

```bash
curl -X POST "https://vergeos.example.com/api/v4/vm_actions" \
  -H "Authorization: Bearer ${VERGEOS_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "vm": 42,
    "action": "poweron"
  }'
```

### 其他操作

一旦虚拟机存在，你就可以通过同一个 `vm_actions` 端点触发高级操作：

```bash
# 克隆虚拟机
curl -X POST ".../api/v4/vm_actions" \
  -d '{"vm": 42, "action": "clone", "params": {"name": "web-server-clone", "quiesce": "true"}}'

# 创建快照
curl -X POST ".../api/v4/vm_actions" \
  -d '{"vm": 42, "action": "snapshot", "params": {"name": "pre-upgrade"}}'

# 平滑关机
curl -X POST ".../api/v4/vm_actions" \
  -d '{"vm": 42, "action": "poweroff"}'
```

## yb-api 辅助脚本

该 `yb-api` 脚本是每个 VergeOS 节点都可通过 SSH 使用的内置命令行封装。它通过为你处理身份验证、请求头、URL 构造、查询编码和上传处理来简化 API 调用。

### 基本语法

```bash
yb-api --get|--post|--put|--delete [options] /v4/<endpoint>
```

### 常用选项

| 标志               | 用途               |
| ---------------- | ---------------- |
| `--get`          | 检索资源             |
| `--post='JSON'`  | 使用 JSON 负载创建资源   |
| `--put='JSON'`   | 使用 JSON 负载更新资源   |
| `--delete`       | 删除资源             |
| `--server=IP`    | 针对特定的 VergeOS 系统 |
| `--user=NAME`    | 以指定用户身份验证        |
| `--fields='...'` | 选择要返回的字段         |
| `--filter='...'` | OData 过滤表达式      |

### 使用示例

```bash
# 列出所有虚拟机（排除快照）及其状态
yb-api --get --user=admin --server=10.0.0.100 \
  --fields='name,$key,ram,machine#status#status as machine_status' \
  --filter='is_snapshot eq false' /v4/vms

# 获取包含磁盘和网卡的详细虚拟机信息
yb-api --get --fields='most,machine[most,drives[most],nics[most]]' /v4/vms/1

# 创建一个新虚拟机
yb-api --post='{"name":"api-vm","enabled":true,"os_family":"linux",
  "cpu_cores":4,"ram":"8192"}' --user=admin --server=10.0.0.100 /v4/vms

# 重命名虚拟机
yb-api --put='{"name":"new-name"}' --user=admin --server=10.0.0.100 /v4/vms/1

# 开机虚拟机
yb-api --post='{"vm":1, "action": "poweron"}' /v4/vm_actions

# 获取 VM 的表模式
yb-api --get '/v4/vms/$table'
```

{% hint style="success" %}
该 `yb-api` 脚本非常适合在 VergeOS 节点上进行快速的临时查询和直接编写脚本。对于从工作站进行远程自动化，请使用 vrg CLI 或 Python/PowerShell SDK。
{% endhint %}

## vrg CLI

该 **vrg** 命令行工具为 VergeOS 提供了一个功能完整的远程管理界面，使用 Python 构建，拥有超过 **200 个命令** ，涵盖虚拟机、网络、存储、租户和系统管理。

### 安装

vrg CLI 通过多种渠道分发——请选择最适合你的环境的方式。它们都不受操作系统限制；在所有受支持的操作系统上，pipx 都是推荐路径。

```bash
# pipx（推荐——隔离的 Python 环境，适用于所有操作系统）
pipx install vrg

# pip（适用于所有操作系统）
pip install vrg

# uv（适用于所有操作系统）
uv tool install vrg

# Homebrew（适用于所有可运行 Homebrew 的操作系统）
brew install verge-io/tap/vrg
```

还发布了一个独立二进制文件（无需 Python）适用于 **Linux x86\_64**, **macOS ARM64**，以及 **Windows x86\_64** ——对于没有 Python 工具链的 Windows 主机很有用。

### 关键功能

### 虚拟机管理

使用简单的命令创建、列出、启动、停止、创建快照、克隆和删除虚拟机。

### 网络操作

管理虚拟网络、防火墙规则、DHCP 设置和 VPN 配置。

### 存储控制

管理 NAS 卷、CIFS/NFS 共享，并监控 vSAN 分层。

### 租户管理

配置租户、分配资源并管理多租户环境。

vrg CLI 封装了上文所记录的同一 REST API，提供标签补全、格式化输出，以及一个更符合日常工作站操作习惯的界面。

## API 错误处理

当 API 调用失败时，VergeOS 会返回标准 HTTP 状态码以及带有描述性的 JSON 错误正文：

| 状态码     | 含义    | 常见原因               |
| ------- | ----- | ------------------ |
| **401** | 未授权   | 凭据无效或令牌已过期         |
| **403** | 禁止    | 该操作权限不足            |
| **404** | 未找到   | 资源不存在或端点无效         |
| **409** | 冲突    | 资源状态冲突（例如：虚拟机已在运行） |
| **422** | 验证错误  | 参数无效或缺少必需字段        |
| **429** | 频率受限  | 超过每小时 1,000 次请求限制  |
| **500** | 服务器错误 | 内部错误——请检查系统日志      |

{% hint style="info" %}
**来自 VMware 或 Nutanix？**

VergeOS 为每个操作提供了一个单一的版本化 `/api/v4/` 操作界面——UI 本身只是该 API 的一个客户端。内置的 Swagger 浏览器由运行系统的实时模式动态生成，因此文档始终与 API 当前接受的内容保持一致。
{% endhint %}

## API 自动化最佳实践

1. **使用 API 密钥** 在生产自动化中使用它们，而不是会话令牌——它们不会因闲置而过期
2. **在 API 密钥上应用 IP 限制** 以限制它们可被使用的位置
3. **选择特定字段** (`fields=name,$key,ram`）而不是 `fields=most` 以减少负载大小
4. **实现分页** 并且彼此之间 `limit` 以及 `offset` 用于大型结果集
5. **处理异步操作** ——像克隆和快照这样的操作会立即返回；轮询 `machine_status` 以等待完成
6. **将凭据存储在环境变量中** ——不要在脚本中硬编码令牌
7. **使用模式自省** (`/$table`）以在编写自动化之前发现可用字段

## 接下来

现在你已经了解了原始 API，接下来的页面将介绍更高层的工具，它们会把这个 API 封装成面向语言的接口：

* **Python SDK（pyvergeos）** ——Python 风格、带类型注解的封装，包含资源管理器和 OData 过滤构建器
* **PowerShell 模块（PSVergeOS）** ——拥有 200+ 个 cmdlet，并支持 Windows 原生自动化的管道


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.verge.io/learn-the-platform/zh/mo-kuai-8-kai-fa-yu-devops/01-api-cli.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
