首页 > 解决方案 > 使用 C# ZabbixAPI 将模板添加到 Zabbix 主机

问题描述

我正在尝试使用这个特定的 nuget 包(版本 1.1.3)将模板添加到 Zabbix(3.0)中的主机。

虽然我能够获取/删除特定的主机和模板,但我无法更新一个。查看用于更新主机的 Zabbix文档,我发现了模板参数的以下描述:

用于替换当前链接模板的模板。未通过的模板仅取消链接。

所以我认为我应该在 host 对象的parentTemplates属性中添加一个模板,并将 host 传递给HostService的Update方法:

Context context = new Context();

var templateService = new TemplateService(context);
Template template = templateService.Get(new { host = "Template_test" }).First();

var hostService = new HostService(context);
Host host = hostService.GetByName("testhost");

host.parentTemplates.Add(template);
hostService.Update(host);

(请注意,这Context context = new Context()将在我使用 .config 文件时起作用。)

编译执行后,程序运行没有错误,但宿主机仍然是无模板的。

有没有人试过这个?我错过了一些明显的东西吗?


Zabbix 配置注意事项:

=== 编辑 ===

提出了四个请求:

最后一个是导致问题。完整的请求在这里

响应:

{"jsonrpc":"2.0","re​​sult":{"hostids":["10135"]},"id":"ca04d839-e6ec-4017-81b0-cc7f8e01fcfc"}

请求是不必要的大。我会检查一下是否可以将其修剪一下。

标签: c#apinugetzabbix

解决方案


如问题评论中所述:参数名称无效。这是因为 Zabbix host.get方法在parentTemplates属性中返回模板,而host.update使用模板

NuGet 的创建者没有考虑到这一点,所以我在他的项目中创建了一个新问题。

我设法通过从Host派生一个类来使我的代码工作:

private class NewHost : Host
{
    public IList<Template> templates { get; set; }
}

然后我可以使用这个类发出请求:

Context context = new Context();

var templateService = new TemplateService(context);
Template template = templateService.Get(new { host = "Template_test" }).First();

var hostService = new HostService(context);
Host host = hostService.GetByName("testhost");

host.parentTemplates.Add(template);

var newhost = new NewHost
{
    Id = host.Id,
    templates = host.parentTemplates
}

hostService.Update(newhost);

多亏了这一点,不仅使用了正确的名称,而且请求正文也更小了。


推荐阅读