mcpField
N
netbox-diode

netbox-diode

github.com/netboxlabs数据与数据库2149 次安装2 周前更新
代码仓库

关于 netbox-diode

netbox-diode 介绍用于通过 Diode 向 NetBox 写入数据的开源 Python 和 Go SDK,面向集成开发者。它以名称引用对象并自动处理依赖,但仅支持写入。

主要功能

  1. 01Python 和 Go SDK 指南
  2. 02按名称引用实体
  3. 03自动解析对象依赖
  4. 04批量写入与分块处理
  5. 05支持 Dry Run 和 OTLP 客户端

适用场景

  1. 01向 NetBox 批量导入或迁移数据
  2. 02提交网络发现结果
  3. 03写入关联的设备、接口和 IP

MCP 相关

文档提到,如已配置 NetBox MCP 服务,可用于验证 Diode 写入的对象。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/netboxlabs/skills --skill netbox-diode

安装后在 Claude Code 中输入/netbox-diode确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
entity-catalog.md
go-sdk-guide.md
ingestion-patterns.md
python-sdk-guide.md

详细介绍

NetBox Diode SDK

Diode 是一种基于 gRPC 的 NetBox 数据采集服务。你无需通过 REST API 管理依赖顺序和对象 ID,只需按名称描述对象,Diode 协调器便会解析依赖关系、创建缺失对象并自动执行 upsert。

本技能涵盖开源 Python 和 Go SDK(diode-sdk-python v1.14.2 / diode-sdk-go v1.12.0),适用于 NetBox 4.5–4.7。两个 SDK 均已针对 NetBox 4.7.0 重新生成实体集(python 1.14.0 / go 1.12.0)。Diode 服务和协调器为专有产品——本技能描述其可观察到的行为,而非内部实现。

你对 Diode SDK 的了解可能已经过时。 实体类型、SDK 方法和协调器行为会随版本演进。请优先检索信息,而非依赖预训练知识。

检索来源

来源URL / 方法用途
Diode 文档https://netboxlabs.com/docs/diode/架构、快速入门
Diode Python SDKhttps://netboxlabs.com/docs/diode/sdk/python/Python SDK 参考
Python SDK 仓库https://github.com/netboxlabs/diode-sdk-python源码、实体类型、变更日志
Go SDK 仓库https://github.com/netboxlabs/diode-sdk-go源码、实体类型、变更日志
Protobuf 参考https://netboxlabs.com/docs/diode/diode-proto/实体架构定义
NetBox MCP 服务若已配置——验证 Diode 创建的对象是否正确写入写入后的验证

如需快速比较 Diode 与 REST API,请参阅 netbox-api-integration/references/diode-integration.md。

首先:验证设置

确认已安装 Diode SDK,并已配置凭据:

# Python
pip show netboxlabs-diode-sdk

# Environment variables (recommended)
echo $DIODE_CLIENT_ID   # Should be set
echo $DIODE_CLIENT_SECRET  # Should be set

如果尚未安装 SDK:pip install netboxlabs-diode-sdk

验证 Diode 服务的连通性:

from netboxlabs.diode.sdk import DiodeClient
with DiodeClient(target="grpc://YOUR_DIODE_HOST:8080/diode", app_name="test", app_version="0.1") as client:
    print("Connected")  # Will raise DiodeConfigError if auth fails

何时使用 Diode

场景推荐方案
网络发现并推送大量对象Diode
批量导入 / 迁移Diode
创建大量相关对象(设备 + 接口 + IP)Diode
读取 / 查询 NetBox 数据REST 或 GraphQL(Diode 仅支持写入)
单个对象的增删改查并立即回读REST API
复杂筛选查询REST 或 GraphQL

相较于 REST 的主要优势: 无需管理依赖顺序、无需查询 ID、自动创建对象,并且具备适用于高数据量场景的 gRPC 性能。

主要限制: 仅支持写入。你无法通过 Diode 查询 NetBox。

快速参考

客户端类型
客户端PythonGo用途
标准DiodeClientdiode.NewClient生产环境数据采集(需要 Diode 服务)
Dry RunDiodeDryRunClientdiode.NewDryRunClient用于测试的 JSON 输出(无需服务)
OTLPDiodeOTLPClientdiode.NewOTLPClient导出为 OpenTelemetry 日志记录
身份验证

推荐通过环境变量使用 OAuth2 客户端凭据:

export DIODE_CLIENT_ID="your-client-id"
export DIODE_CLIENT_SECRET="your-client-secret"

也可直接传入:client_id= / client_secret=(Python),WithClientID() / WithClientSecret()(Go)。

最简 Python 示例
from netboxlabs.diode.sdk import DiodeClient
from netboxlabs.diode.sdk.ingester import Device, Interface, IPAddress, Entity

with DiodeClient(
    target="grpc://localhost:8080/diode",
    app_name="my-discovery",
    app_version="1.0.0",
) as client:
    entities = [
        Entity(device=Device(
            name="sw-01",
            device_type="Catalyst 9300",
            manufacturer="Cisco",
            site="NYC-DC1",
            role="Access Switch",
            status="active",
        )),
        Entity(interface=Interface(device="sw-01", name="Gi0/1", type="1000base-t")),
        Entity(ip_address=IPAddress(address="10.0.1.1/24")),
    ]
    response = client.ingest(entities=entities)
    if response.errors:
        for err in response.errors:
            print(f"Error: {err}")
最简 Go 示例
import diode "github.com/netboxlabs/diode-sdk-go/diode"  // exported types live in the diode/ subpackage

client, err := diode.NewClient(
    "grpc://localhost:8080/diode",
    "my-discovery",
    "1.0.0",
    diode.WithClientID("YOUR_CLIENT_ID"),
    diode.WithClientSecret("YOUR_CLIENT_SECRET"),
)
if err != nil { log.Fatal(err) }
defer client.Close()

entities := []diode.Entity{
    &diode.Device{
        Name:       diode.String("sw-01"),
        DeviceType: &diode.DeviceType{Model: diode.String("Catalyst 9300")},
        Site:       &diode.Site{Name: diode.String("NYC-DC1")},
        Role:       &diode.DeviceRole{Name: diode.String("Access Switch")},
        Status:     diode.String("active"),
    },
}
resp, err := client.Ingest(context.Background(), entities)

构造实体

字符串简写(仅 Python)

对于主键位于 PRIMARY_VALUE_MAP 中的 Python 实体,可在嵌套引用中使用字符串简写:

# These are equivalent:
Device(name="sw-01", site="NYC-DC1")
Device(name="sw-01", site=Site(name="NYC-DC1"))

如果需要设置主键以外的属性,请使用完整对象:

Device(name="sw-01", site=Site(name="NYC-DC1", status="active", region="US-East"))

Go 不支持字符串简写。 始终使用完整结构体类型及指针辅助函数(diode.String()、diode.Int())。

必需字段

大多数实体只需提供其主要标识字段(例如,Device 的 name,IPAddress 的 address)。协调器会自动创建被引用的对象。完整列表请参阅 references/entity-catalog.md。

唯一性约束
实体唯一标识
设备name + site + tenant
接口name + device
IP 地址address + vrf
前缀prefix + vrf
VLANvid + group

协调器行为

协调器是处理已摄取数据的服务端组件。其可观察到的主要行为:

  1. 自动解析依赖项 — 引用 site="NYC-DC1" 时,如果该站点不存在,就会创建它
  2. 按名称匹配 — 根据对象的主要标识字段进行匹配
  3. 无需排序 — 与 REST 不同,你无需先创建制造商,再创建设备类型
  4. 更新或插入语义 — 匹配的实体会被更新,而不会重复创建
  5. 自动生成 slug — 如果未提供 slug,则根据 name 生成
  6. 区分大小写匹配 — "Site ABC" ≠ "site abc"
  7. 生产者来源信息 — 实体会标记 app_name / app_version,以供审计

数据摄取模式

批量摄取

在一次调用中发送多个实体:

response = client.ingest(entities=[
    Entity(device=device1),
    Entity(device=device2),
    Entity(interface=iface1),
], metadata={"batch_id": "scan-001"})
分块摄取(大批量数据)

gRPC 的消息大小上限约为 4MB。大负载请使用内置分块功能:

from netboxlabs.diode.sdk import create_message_chunks

for chunk in create_message_chunks(entities):  # default 3MB chunks
    client.ingest(entities=chunk)

Go:client.Ingest(ctx, entities, diode.WithChunking(0))(0 = 默认 3MB)。

试运行和 OTLP

有关试运行测试、重放和 OTLP 导出的信息,请参阅 references/ingestion-patterns.md。

错误处理

Python 异常层级
DiodeConfigError          # Bad credentials, unreachable auth endpoint
DiodeClientError          # gRPC transport errors (inherits grpc.RpcError; has .code(), .details())
OTLPClientError           # OTLP export failures

注意: DiodeClientError 继承自 grpc.RpcError,因此 except grpc.RpcError 也会捕获它。

认证过期时自动重试及认证退避

两个 SDK 都会针对 UNAUTHENTICATED gRPC 错误(令牌过期)进行重试,默认最多 3 次(max_auth_retries / DIODE_MAX_AUTH_RETRIES)。同一限制也适用于 OAuth2 令牌请求本身:

  • 令牌获取退避 (python 1.13+,go 1.10+):如果 /auth/token 返回 429、500、502 或 503,则使用指数退避重试(从 1s 开始,每次翻倍,最高 30s,并加入抖动);遇到 429 / 503 时遵循 Retry-After。任何其他非 200 状态都会立即失败,并返回 DiodeConfigError(Python)/ authentication failed 错误(Go)。
  • 主动刷新 (go 1.11.1+):Go 客户端会在访问令牌的 expires_in 有效期结束前约一分钟续订令牌,并将并发刷新合并为单个令牌请求。Python 客户端仅在收到 UNAUTHENTICATED 响应后重新认证。
  • 将 DIODE_MAX_AUTH_RETRIES=1 设为仅尝试一次,不进行重试(Go 会拒绝 ≤ 0 的值;Python 不会验证该值)。
推荐模式
from netboxlabs.diode.sdk.exceptions import DiodeClientError, DiodeConfigError

try:
    with DiodeClient(target=target, app_name="app", app_version="1.0") as client:
        response = client.ingest(entities=entities)
        if response.errors:  # Per-entity validation errors
            for err in response.errors:
                log.warning(f"Entity error: {err}")
except DiodeConfigError as e:
    log.error(f"Config/auth error: {e}")
except DiodeClientError as e:
    log.error(f"gRPC error: {e.status_code} - {e.details}")

反模式

  1. IPAddress 必须使用 CIDR — "192.168.1.1/24",而不是 "192.168.1.1"
  2. Interface 必须指定设备 — 没有设备上下文时,仅凭名称无法保证唯一
  3. Go 不支持字符串简写 — 每个嵌套引用都需要完整的结构体
  4. Diode 仅支持写入 — 使用 REST/GraphQL 读取数据
  5. 区分大小写匹配 — 大小写不一致会创建重复对象
  6. gRPC 4MB 上限 — 大批量数据请使用分块功能
  7. 字符串简写的限制 — 无法设置嵌套对象的属性(请使用完整对象)
  8. 元数据必须兼容 JSON — 仅支持字符串、数字、布尔值、列表和字典
  9. NetBox 4.7 中的服务端口 — 使用 port_mappings=["tcp/53", "udp/53"];protocol + ports 仍可使用,但在 NetBox 4.7 中已弃用(将在 5.0 中从 API 移除),且仅用于描述单协议服务

版本说明

NetBox 4.7(2026-09-02)— SDK python 1.14.x / go 1.12.0
  • 新增实体类型:CoolingSource、CoolingFeed、CoolingIntake、CoolingOutflow、ModuleBayType,以及精简版 User(仅用作 RackReservation.user)。仅针对 NetBox 4.7 且配有匹配版本 Diode 插件的环境摄取这些实体。
  • 新增字段:Device.cooling_method;DeviceType/ModuleType.cooling_method + end_of_life;ModuleType/ModuleBay.module_bay_types;Rack/RackType.cooling_capability + cooling_capacity;Interface.channels + channel_id(通道化子接口)和可写的 Interface.mac_address;Service.port_mappings。完整列表见 references/entity-catalog.md。
  • **读取 Diode 在 4.7 中写入的数据:**选择型自定义字段通过 REST/GraphQL 返回时会变成 {"value": ..., "label": ...} 对象;默认情况下,设备/VM 会包含 config_context(在 4.7.3+ 中可通过 ?omit=config_context 将其省略)。请参阅 netbox-api-integration。
  • **python 1.14.2(2026-10-06):**现在,DIODE_SKIP_TLS_VERIFY=true 会保持连接使用 TLS,并且只跳过证书验证;早期版本会改用明文通道。详情见 references/python-sdk-guide.md。
NetBox 4.6 — SDK python 1.12.0 / go 1.9.0
  • 新增 CableBundle、RackGroup、VirtualMachineType、ScriptModule、DeviceConfig。

参考资料

文件加载时机
references/entity-catalog.md需要查看 110 种实体类型及其字段的完整列表,包括 NetBox 4.7 新增内容时
references/python-sdk-guide.md构建 Python 集成——设置、模式和示例
references/go-sdk-guide.md构建 Go 集成——设置、模式和示例
references/ingestion-patterns.md高级模式:分块、试运行、OTLP、元数据
跨技能参考

评论

支持 Markdown