> 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/automate-protect-and-extend/zh/ji-cheng-yu-api/vrg-cli.md).

# VergeOS CLI（vrg）

## 概述

`vrg` 是 VergeOS 的官方命令行界面。它提供 200+ 条命令，涵盖计算、网络、租户、NAS、身份、自动化和监控，并支持声明式 `.vrg.yaml` 用于可复现、受版本控制的配置的 VM 模板。可用于以终端为先的管理、Shell 脚本和 CI/CD 流水线。

## 要求

* Python 3.10 或更高版本（在通过 `pip`, `pipx`，或 `uv`)
* 在 VergeOS 实例上具有相应权限的用户账户或 API 密钥

## 安装

`vrg` 可以通过多种方式安装。 `pipx` 推荐，因为它会将 CLI 隔离在其自己的虚拟环境中。

### pipx（推荐）

```bash
pipx install vrg
```

### pip

```bash
pip install vrg
```

### uv

```bash
uv tool install vrg
```

### Homebrew

```bash
brew install verge-io/tap/vrg
```

### 独立二进制文件

从 [最新发布版本](https://github.com/verge-io/vrg/releases/latest) 下载预构建二进制文件，然后将其放到你的 `PATH`。二进制文件适用于 Linux（x86\_64）、macOS（ARM64）和 Windows（x86\_64）。

{% hint style="warning" %}
**macOS 隔离**

在 macOS 上，独立二进制文件可能会被 Gatekeeper 隔离。运行前移除该属性：

```bash
xattr -d com.apple.quarantine ./vrg
```

{% endhint %}

安装后，使用以下命令验证：

```bash
vrg --version
```

### 升级

| 安装方式     | 升级命令                                                        |
| -------- | ----------------------------------------------------------- |
| `pipx`   | `pipx upgrade vrg`                                          |
| `pip`    | `pip install --upgrade vrg`                                 |
| `uv`     | `uv tool upgrade vrg`                                       |
| Homebrew | `brew upgrade vrg`                                          |
| 独立版      | 重新从 [发布页面](https://github.com/verge-io/vrg/releases/latest) |

## 快速开始

```bash
# 1. 配置凭据（交互式向导）
vrg configure setup

# 2. 验证连接
vrg system info

# 3. 边用边发现命令 — 每个命令都支持 --help
vrg --help
vrg vm --help

# 4. 列出你的虚拟机
vrg vm list
```

`vrg configure setup` 是一个交互式向导，会提示输入主机 URL、认证方式和默认输出格式。它会将结果保存到 `~/.vrg/config.toml`。详情请参见 [身份验证](#authentication) ，了解每种方法的细节以及如何编写凭据脚本。

## 身份验证

`vrg` 支持四种认证方式。四种方式都可以通过交互式向导、环境变量、命令行标志或 `~/.vrg/config.toml`.

| 方式            | 最佳用途        | 提供方式                                          |
| ------------- | ----------- | --------------------------------------------- |
| **Bearer 令牌** | CI 流水线、脚本   | `--token` 标志或 `VERGE_TOKEN` 环境变量              |
| **API 密钥**    | 长期运行的服务自动化  | `--api-key` 标志                                |
| **用户名 + 密码**  | 交互式会话、一次性任务 | `--username` / `--password` 或向导提示             |
| **配置文件**      | 多个实例        | `--profile <name>` 在运行后 `vrg configure setup` |

### 生成 API 密钥

API 密钥既可在 VergeOS UI（系统 → API 密钥）中管理，也可以在通过其他方式完成认证后直接通过 CLI 管理：

```bash
# 在首次交互式登录后，为 CI 生成一个长期有效的密钥
vrg api-key create --name ci-pipeline
vrg api-key list
```

将返回值视为机密——将其存储在 CI 提供商的密钥管理器中，切勿放入源代码控制。

### 环境变量

环境变量会覆盖配置文件中的值，因此它们非常适合 CI/CD：

```bash
export VERGE_HOST=https://verge.example.com
export VERGE_TOKEN=eyJhbGc...
vrg vm list
```

### 配置文件

配置文件可让你在多个 VergeOS 实例（生产、预发、客户环境）之间切换：

```bash
vrg configure setup --profile prod   # Set up a named profile
vrg configure list                   # List configured profiles
vrg configure show                   # Show active profile (credentials masked)
vrg --profile prod vm list           # Use a specific profile for one command
vrg -p staging vm list               # Short form
```

{% hint style="success" %}
**跨配置文件查询**

在 `--all-profiles` 上使用列表命令，即可针对每个已配置的配置文件运行。每一行输出都包含一个 `配置文件` 列，用于显示它来自哪里。
{% endhint %}

## 命令模式

所有 `vrg` 命令都遵循一致的结构：

```
vrg [global-options] <domain> [sub-domain] <action> [arguments] [options]
```

大多数资源都实现了标准 CRUD 操作： `列表`, `获取`, `创建`, `更新`和 `删除`。破坏性操作需要 `--yes` 以跳过确认提示。

### 命令域

| 域           | 子域                                                                                                                    |
| ----------- | --------------------------------------------------------------------------------------------------------------------- |
| **计算**      | `vm`, `vm drive`, `vm nic`, `vm device`, `vm snapshot`, `vm export`, `vm import`                                      |
| **网络**      | `网络`, `network rule`, `network dns`, `network host`, `network alias`, `network diag`, `network query`                 |
| **租户**      | `租户`, `tenant node`, `tenant storage`, `tenant net`, `tenant snapshot`, `tenant stats`, `tenant share`, `tenant logs` |
| **NAS**     | `nas service`, `nas volume`, `nas cifs`, `nas nfs`, `nas user`, `nas sync`, `nas files`                               |
| **基础设施**    | `集群`, `节点`, `存储`                                                                                                      |
| **快照**      | `快照`, `快照配置文件`                                                                                                        |
| **站点与复制**   | `站点`, `站点同步出站`, `站点同步入站`                                                                                              |
| **身份与访问**   | `用户`, `组`, `权限`, `API 密钥`, `认证源`                                                                                      |
| **证书与单点登录** | `证书`, `OIDC`                                                                                                          |
| **自动化**     | `任务`, `任务计划`, `任务触发器`, `任务事件`, `任务脚本`                                                                                 |
| **配方**      | `配方`, `配方章节`, `配方问题`, `配方实例`, `配方日志`                                                                                  |
| **目录**      | `目录`, `目录仓库`                                                                                                          |
| **更新**      | `更新`, `更新源`, `更新分支`, `更新包`, `有可用更新`                                                                                   |
| **监控**      | `告警`, `告警历史`, `日志`                                                                                                    |
| **标签**      | `标签`, `标签分类`, `资源组`                                                                                                   |
| **系统**      | `系统`, `系统设置`, `系统许可证`, `系统诊断`, `doctor`, `配置`, `文件`, `补全`                                                             |

完整参考信息维护在 [命令参考](https://github.com/verge-io/vrg/blob/main/docs/COMMANDS.md) .

## 使用示例

### 列出并检查虚拟机

```bash
# 列出所有虚拟机
vrg vm list

# 检查单个虚拟机
vrg vm get web-server

# 电源状态
vrg vm start web-server --wait    # --wait 会阻塞直到虚拟机运行
vrg vm stop web-server --wait
vrg vm restart web-server
```

### 从 Shell 标志构建虚拟机

Shell 标志方式适合快速试验。若要进行可重复的配置，请参见 [VM 模板](#vm-templates).

```bash
# 创建虚拟机（--ram 以 MB 为单位）
vrg vm create --name web-server --ram 4096 --cpu 2

# 添加一个 50 GB 磁盘并附加一个 NIC
vrg vm drive create web-server --size 50GB --name os-disk
vrg vm nic create web-server --network External

# 启动虚拟机
vrg vm start web-server --wait
```

{% hint style="info" %}
**空虚拟机不会启动**

通过 shell 标志创建的虚拟机未附加操作系统。若要安装系统，可从 ISO 驱动器引导（`vrg vm drive create … --media cdrom`）、克隆现有虚拟机（`vrg vm clone`），或在 `.vrg.yaml` 模板
{% endhint %}

### 使用网络

```bash
# 创建带 DHCP 的内部网络
vrg network create --name dev-net --cidr 10.0.0.0/24 --ip 10.0.0.1 --dhcp
vrg network start dev-net

# 允许入站 SSH（--dest-ports 接受单个端口、范围 "80-443"，或 "80,443"）
vrg network rule create dev-net \\
  --name allow-ssh --action accept --direction incoming \\
  --protocol tcp --dest-ports 22

# 应用待处理的防火墙更改
vrg network apply-rules dev-net
```

### 网络与节点诊断

`vrg` 提供可在网络的虚拟路由器上运行，或直接在物理节点上运行的诊断查询：

```bash
# 网络连通性测试
vrg network query ping External 8.8.8.8
vrg network query traceroute External 8.8.8.8
vrg network query dns External example.com

# 节点硬件检查
vrg node query smartctl node1 /dev/sda
vrg node query ipmi-sensor node1
vrg node lldp list node1
```

### 系统健康检查

```bash
# 运行所有内置健康检查
vrg doctor

# 运行特定子集
vrg doctor --check connectivity,clusters,nodes,storage

# 自动化用 JSON 输出；退出码 0 = 健康，1 = 失败
vrg -o json doctor | jq '.[] | select(.status == "fail")'
```

## VM 模板

将虚拟机定义为 `.vrg.yaml` 文件，以实现可重复、受版本控制的配置。模板支持变量、dry-run 预览、通过 `--set`运行时覆盖、cloud-init，以及使用 `VirtualMachineSet`.

### 示例模板

将以下内容保存为 `web-server.vrg.yaml`:

```yaml
apiVersion: v4
kind: VirtualMachine

vm:
  name: web-server-01
  os_family: linux
  cpu_cores: 4
  ram: 8GB
  machine_type: q35
  uefi: true
  guest_agent: true

  cloudinit:
    datasource: nocloud
    files:
      - name: user-data
        content: |
          #cloud-config
          hostname: web-server-01
          packages:
            - nginx
            - qemu-guest-agent
          runcmd:
            - systemctl enable --now nginx

  drives:
    - name: "OS Disk"
      media: disk
      interface: virtio-scsi
      size: 50GB

  nics:
    - name: "Primary"
      interface: virtio
      network: External
```

### 验证并创建

```bash
# 根据 schema 验证模板
vrg vm validate -f web-server.vrg.yaml

# 在不做更改的情况下预览操作
vrg vm create -f web-server.vrg.yaml --dry-run

# 创建虚拟机
vrg vm create -f web-server.vrg.yaml

# 在运行时覆盖字段
vrg vm create -f web-server.vrg.yaml \\
  --set vm.name=web-server-02 --set vm.ram=16GB
```

{% hint style="success" %}
**变量与默认值**

模板支持 `${VAR}` 来自环境变量的替换或一个 `vars：` 代码块，以及默认值语法（`${VM_RAM:-4GB}`）。这对于在不同环境中对单个模板进行参数化很有用。
{% endhint %}

有关完整的模板字段参考，请参见 [模板指南](https://github.com/verge-io/vrg/blob/main/docs/TEMPLATES.md) .

## 输出格式

所有命令都支持 `--output` （或 `-o`）用于更改输出格式，并 `--query` 用于使用点表示法提取字段。

| 格式      | 使用场景                        |
| ------- | --------------------------- |
| `table` | 默认的人类可读输出                   |
| `wide`  | 所有可用列，包括默认视图中隐藏的列           |
| `json`  | 适合通过管道传递给 `jq` 或其他工具的机器可读输出 |
| `csv`   | 适合电子表格的导出                   |

```bash
# 所有列
vrg -o wide vm list

# 用于脚本的 JSON
vrg -o json vm list | jq '.[].name'

# CSV 导出
vrg -o csv vm list > vms.csv

# 使用点表示法提取单个字段（支持嵌套路径）
vrg --query status vm get web-server
vrg --query nics[0].network vm get web-server
```

## Shell 补全

bash、zsh、fish 和 PowerShell 都支持 Tab 补全。启用它的最快方法是：

```bash
vrg --install-completion
```

{% hint style="warning" %}
**macOS zsh：不安全的目录**

如果你看到 `compinit: insecure directories` 在 macOS 上安装补全后，请修复 Homebrew 目录权限：

```bash
chmod 755 /opt/homebrew/share/zsh /opt/homebrew/share/zsh/site-functions
```

{% endhint %}

## 全局选项

| 选项               | 简写   | 描述                                   |
| ---------------- | ---- | ------------------------------------ |
| `--profile`      | `-p` | 要使用的配置文件                             |
| `--host`         | `-H` | VergeOS 主机 URL（覆盖）                   |
| `--token`        |      | 用于身份验证的 Bearer 令牌                    |
| `--api-key`      |      | 用于身份验证的 API 密钥                       |
| `--username`     | `-u` | 基础认证用户名                              |
| `--password`     |      | 基础认证密码                               |
| `--output`       | `-o` | 输出格式（`table`, `wide`, `json`, `csv`) |
| `--query`        |      | 使用点表示法提取字段                           |
| `--all-profiles` |      | 在所有已配置的配置文件上运行列表命令                   |
| `--verbose`      | `-v` | 增加详细输出（`-v`, `-vv`, `-vvv`)          |
| `--quiet`        | `-q` | 抑制非必要输出                              |
| `--no-color`     |      | 禁用彩色输出                               |
| `--yes`          |      | 在破坏性操作中跳过确认提示                        |
| `--version`      | `-V` | 显示版本                                 |
| `--help`         |      | 显示帮助                                 |

## 退出代码

`vrg` 为脚本和 CI 集成使用有意义的退出代码：

| 代码 | 含义          |
| -- | ----------- |
| 0  | 成功          |
| 1  | 通用错误        |
| 2  | 无效参数        |
| 3  | 配置错误        |
| 4  | 身份验证错误      |
| 5  | 权限被拒绝       |
| 6  | 未找到资源       |
| 7  | 冲突（例如，名称重复） |
| 8  | 验证错误        |
| 9  | 超时          |
| 10 | 连接错误        |

## 故障排除

| 症状                                       | 可能原因          | 解决方法                                                                       |
| ---------------------------------------- | ------------- | -------------------------------------------------------------------------- |
| 退出代码 4                                   | 身份验证失败        | 运行 `vrg configure setup` 并验证令牌、API 密钥或凭据                                   |
| 退出代码 3                                   | 配置错误          | 检查 `~/.vrg/config.toml` 或运行 `vrg configure show`                           |
| 退出代码 10                                  | 连接错误          | 验证 `VERGE_HOST` 是否可访问且 URL 正确                                              |
| `compinit: insecure directories` （macOS） | Homebrew 权限   | `chmod 755 /opt/homebrew/share/zsh /opt/homebrew/share/zsh/site-functions` |
| `vrg` 在 macOS 上被阻止                       | Gatekeeper 隔离 | `xattr -d com.apple.quarantine ./vrg`                                      |

## 选择合适的工具

`vrg` 是 VergeOS 的多个自动化接口之一。请根据你的工作方式选择：

| 工具                                                                                      | 适用场景                                   |
| --------------------------------------------------------------------------------------- | -------------------------------------- |
| **vrg CLI**                                                                             | 你主要在终端中工作，想要声明式 VM 模板，或者需要一次性脚本        |
| [Python SDK](/automate-protect-and-extend/zh/ji-cheng-yu-api/python-sdk.md)             | 你正在编写 Python 应用、复杂自动化，或与其他 Python 工具集成 |
| [PowerShell 模块](/automate-protect-and-extend/zh/ji-cheng-yu-api/powershell-module.md)   | 你们以 Windows 为主，或已经使用 PowerShell 进行自动化  |
| [Terraform 提供程序](/automate-protect-and-extend/zh/ji-cheng-yu-api/terraform-provider.md) | 你与其他由 Terraform 管理的基础设施一起管理 VergeOS    |
| [Go SDK](/automate-protect-and-extend/zh/ji-cheng-yu-api/go-sdk.md)                     | 你正在将 VergeOS 管理功能嵌入到 Go 应用程序中          |

## 资源与支持

* [GitHub 仓库](https://github.com/verge-io/vrg) — 源码、问题和发布
* [命令参考](https://github.com/verge-io/vrg/blob/main/docs/COMMANDS.md) — 每个命令和标志
* [模板指南](https://github.com/verge-io/vrg/blob/main/docs/TEMPLATES.md) — 完整 `.vrg.yaml` 字段参考
* [食谱](https://github.com/verge-io/vrg/blob/main/docs/COOKBOOK.md) — 面向任务的示例
* [架构](https://github.com/verge-io/vrg/blob/main/docs/ARCHITECTURE.md) — 设计与内部原理
* [已知问题](https://github.com/verge-io/vrg/blob/main/docs/KNOWN_ISSUES.md) — 当前限制和解决方法
* [PyPI 包](https://pypi.org/project/vrg/)
* [报告问题](https://github.com/verge-io/vrg/issues)
* [VergeOS API 文档](/knowledge-base/zh/automation-api/verge-api-guide.md)


---

# 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/automate-protect-and-extend/zh/ji-cheng-yu-api/vrg-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.
