> 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/python-sdk.md).

# VergeOS Python SDK（pyvergeos）

## 概述

pyvergeos 是一个 Python SDK，用于通过 REST API 管理 VergeOS 基础设施。它提供了一个符合 Python 风格、带类型注解的接口，可用于自动化虚拟机生命周期、网络、存储、多租户操作和灾难恢复工作流，非常适合自动化脚本、工具开发和集成。

## 主要功能

* **虚拟机管理**：创建、配置、电源控制、克隆和快照
* **高级网络**：虚拟网络、防火墙规则、DHCP、DNS、IPSec VPN 和 WireGuard
* **NAS 与存储**：卷管理、CIFS/NFS 共享和同步
* **多租户**：带资源隔离的租户预配
* **灾难恢复**：云快照、站点同步和恢复工作流
* **过滤**：支持 OData 过滤，带流式过滤构建器 API
* **类型注解**：为 IDE 自动补全和静态分析提供完整类型提示
* **跨平台**：支持 Windows、macOS 和 Linux

## 要求

* Python 3.9 或更高版本
* VergeOS 26.0 或更高版本

## 安装

### 从 PyPI 安装（推荐）

```bash
pip install pyvergeos
```

### 使用 uv

```bash
uv add pyvergeos
```

### 从源码安装

```bash
git clone https://github.com/verge-io/pyvergeos.git
cd pyvergeos
pip install .
```

## 身份验证

该 SDK 支持多种身份验证方式：

### 用户名/密码

```python
from pyvergeos import VergeClient

client = VergeClient(
    host="192.168.1.100",
    username="admin",
    password="secret",
    verify_ssl=False  # 适用于自签名证书
)
```

{% hint style="info" %}
**SSL 证书验证**

设置 `verify_ssl=False` 仅用于使用自签名证书的环境。对于具有有效证书的生产环境，请省略此参数或将其设置为 `True`.
{% endhint %}

### API 令牌

```python
client = VergeClient(
    host="192.168.1.100",
    token="your-api-token"
)
```

### 环境变量

```bash
export VERGE_HOST=192.168.1.100
export VERGE_USERNAME=admin
export VERGE_PASSWORD=secret
```

```python
client = VergeClient.from_env()
```

{% hint style="success" %}
**生产环境推荐**

使用环境变量可避免在源代码中暴露凭据，并且便于在不同环境中使用不同凭据。
{% endhint %}

### 上下文管理器

```python
with VergeClient(host="192.168.1.100", token="api-token") as client:
    vms = client.vms.list()
```

{% hint style="success" %}
**自动清理**

使用上下文管理器（`with` 语句）可确保连接被正确关闭，即使发生异常也是如此。
{% endhint %}

## 可用资源

该 SDK 可访问以下 VergeOS 资源：

| 类别      | 资源                        |
| ------- | ------------------------- |
| 虚拟机     | 虚拟机、磁盘、网卡、快照              |
| 网络      | 网络、规则、DNS、DHCP、别名、主机      |
| VPN     | IPSec 连接、WireGuard 接口和对等端 |
| NAS/存储  | 服务、卷、CIFS/NFS 共享、卷同步      |
| 租户      | 租户管理、快照、存储、网络块            |
| 用户和组    | 用户、组、权限、API 密钥            |
| 系统      | 集群、节点、存储层级、证书             |
| 监控      | 告警、日志、任务                  |
| 备份与灾难恢复 | 快照配置文件、云快照、站点、站点同步        |

## 使用示例

### 管理虚拟机

```python
from pyvergeos import VergeClient

client = VergeClient(host="192.168.1.100", username="admin", password="secret")

# 列出所有虚拟机
for vm in client.vms.list():
    print(f"{vm.name}: {vm.ram}MB RAM, {vm.cpu_cores} cores")

# 获取特定虚拟机
vm = client.vms.get(name="web-server")

# 创建虚拟机
new_vm = client.vms.create(
    name="test-vm",
    ram=2048,
    cpu_cores=2,
    os_family="linux"
)

# 电源操作
vm.power_on()
vm.power_off()
vm.reset()

# 快照
vm.snapshot(retention=86400, quiesce=True)

# 克隆虚拟机
clone = vm.clone(name="test-clone")

# 添加磁盘和网卡
vm.drives.add(name="data", size=50*1024*1024*1024)
vm.nics.add(network=network.key)

client.disconnect()
```

### 创建和管理网络

```python
# 创建虚拟网络
network = client.networks.create(
    name="app-network",
    network_address="10.10.1.0/24",
    ip_address="10.10.1.1",
    dhcp_enabled=True
)

network.power_on()
network.apply_rules()

# 添加防火墙规则
network.rules.create(
    name="Allow SSH",
    action="accept",
    protocol="tcp",
    dest_port=22
)
```

### 过滤资源

该 SDK 支持多种过滤方式：

{% tabs %}
{% tab title="关键字参数" %}

```python
# 适用于基础过滤，简单易读
vms = client.vms.list(status="running", name="prod-*")
```

{% endtab %}

{% tab title="OData 过滤字符串" %}

```python
# 复杂查询使用完整的 OData 过滤语法
vms = client.vms.list(filter="os_family eq 'linux' and ram gt 2048")
```

{% endtab %}

{% tab title="过滤构建器" %}

```python
# 用于以编程方式构建过滤条件的流式 API
from pyvergeos import Filter

f = Filter().eq("os_family", "linux").and_().gt("ram", 2048)
vms = client.vms.list(filter=str(f))
```

{% endtab %}
{% endtabs %}

### 等待任务

VergeOS 中的许多操作都是异步执行的。使用任务管理器等待完成：

```python
result = vm.snapshot()
task = client.tasks.wait(result["task"], timeout=300)
```

{% hint style="info" %}
**异步操作**

快照、克隆和迁移等操作会立即返回一个任务 ID。使用 `client.tasks.wait()` 来阻塞，直到操作完成。
{% endhint %}

## 错误处理

该 SDK 为不同错误条件提供了特定的异常类型：

```python
from pyvergeos import NotFoundError, AuthenticationError, TaskTimeoutError

try:
    vm = client.vms.get(name="nonexistent")
except NotFoundError:
    print("未找到虚拟机")

try:
    task = client.tasks.wait(task_id, timeout=60)
except TaskTimeoutError as e:
    print(f"任务 {e.task_id} 超时")
```

{% hint style="info" %}
**可用异常类型**
{% endhint %}

| 异常                    | 描述                 |
| --------------------- | ------------------ |
| `VergeError`          | 所有 SDK 错误的基础异常     |
| `AuthenticationError` | 凭据无效或令牌已过期         |
| `NotFoundError`       | 请求的资源不存在           |
| `ConflictError`       | 资源状态冲突（例如：虚拟机已在运行） |
| `ValidationError`     | 参数值无效              |
| `TaskTimeoutError`    | 任务未在超时时间内完成        |
| `TaskError`           | 任务在执行期间失败          |

## 常见用例

* **基础设施自动化**：以编程方式预配虚拟机、网络和存储
* **CI/CD 集成**：在流水线中创建和销毁测试环境
* **监控和报告**：查询资源状态并生成清单报告
* **备份自动化**：安排并管理快照和云备份
* **多租户预配**：自动化租户创建和资源分配

## 文档与资源

完整文档（包括所有可用方法和详细使用示例）请访问官方仓库：

* [GitHub 仓库](https://github.com/verge-io/pyvergeos)
* [PyPI 包](https://pypi.org/project/pyvergeos/)

## 支持

如果您遇到问题或有功能请求，请在 GitHub 仓库中提交 issue：

<https://github.com/verge-io/pyvergeos/issues>

## 其他资源

* [Python 文档](https://docs.python.org/3/)
* [VergeOS API 文档](/knowledge-base/zh/automation-api/verge-api-guide.md)
* [PSVergeOS PowerShell 模块](/automate-protect-and-extend/zh/ji-cheng-yu-api/powershell-module.md) - PowerShell 替代方案
* [Terraform 提供程序](/automate-protect-and-extend/zh/ji-cheng-yu-api/terraform-provider.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/python-sdk.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.
