简介: 利用zabbix api批量添加监控主机 在公司规模很庞大的时候,每次都手动添加监控主机将会很麻烦,我们可以利用zabbix的api去批量添加监控主机 本次我们将实现用一台主机虚拟出100台主机,并通过api的方式自动添加监控主机

利用zabbix api批量添加监控主机

在公司规模很庞大的时候,每次都手动添加监控主机将会很麻烦,我们可以利用zabbix的api去批量添加监控主机

本次我们将实现用一台主机虚拟出100台主机,并通过api的方式自动添加监控主机

掌握本次方法,无需要了解python,也不需要写python脚本

1.获取批量添加主机的api

可以从官网取到https://www.zabbix.com/documentation/4.0/zh/manual/api/reference/host/create

  1. {
  2. "jsonrpc": "2.0",
  3. "method": "host.create",
  4. "params": {
  5. "host": "192.168.81.180",
  6. "interfaces": [
  7. {
  8. "type": 1,
  9. "main": 1,
  10. "useip": 1,
  11. "ip": "192.168.81.180",
  12. "dns": "",
  13. "port": "10050"
  14. }
  15. ],
  16. "groups": [
  17. {
  18. "groupid": "15"
  19. }
  20. ],
  21. "templates": [
  22. {
  23. "templateid": "10271"
  24. }
  25. ]
  26. },
  27. "auth": "'$token'",
  28. "id": 1
  29. }

:::info api必要字段说明
解释:
“host”: “192.168.81.160”, #主机名称
“interfaces”: [
{undefined
“type”: 1, #使用agent客户端
“main”: 1, #默认
“useip”: 1, #ip地址
“ip”: “192.168.81.160”, #agent的地址
“dns”: “”,
“port”: “10050” #agent端口
}
],
“groups”: [
{undefined
“groupid”: “15” #主机群组的id
}
],
“templates”: [
{
“templateid”: “10271” #模板id
}
] :::

2.创建一百台服务器

我们虽然没有一百台服务器,但是我们可以创建100个网卡,且都在一台机器上,有一百个ip即可

  1. [root@k8s-master ~\]# for i in {100..200}
  2. do
  3. ifconfig ens33:$i 192.168.81.$i
  4. ifconfig ens33 up
  5. done

zabbix api批量添加数百台监控主机 - 图1

3.编写批量添加主机的脚本

3.1.将一百台机器的ip写到文件中

  1. [root@k8s-master ~\]# echo 192.168.81.{100..200} | xargs -n1 > /root/host.txt

3.2.在机器上安装zabbix-agent

  1. [root@k8s-master ~\]# yum -y install zabbix-agent
  2. [root@k8s-master ~\]# vim /etc/zabbix/zabbix_agentd.conf Server=192.168.81.250
  3. [root@k8s-master ~\]# systemctl restart zabbix-agent

3.3.编写批量添加主机的脚本

  1. [root@k8s-master ~]# vim zabbix_host_creates.sh
  2. #!/bin/bash
  3. #批量添加zabbix主机
  4. #登陆
  5. token=`echo $json | grep result | awk -F'"' '{print $10}'`
  6. #批量添加主机
  7. for ip in `cat /root/host.txt`
  8. do
  9. curl -s -X POST -H 'Content-Type: application/json' -d '
  10. {
  11. "jsonrpc": "2.0",
  12. "method": "host.create",
  13. "params": {
  14. "host": "'$ip'",
  15. "interfaces": [
  16. {
  17. "type": 1,
  18. "main": 1,
  19. "useip": 1,
  20. "ip": "'$ip'",
  21. "dns": "",
  22. "port": "10050"
  23. }
  24. ],
  25. "groups": [
  26. {
  27. "groupid": "15"
  28. }
  29. ],
  30. "templates": [
  31. {
  32. "templateid": "10271"
  33. }
  34. ]
  35. },
  36. "auth": "'$token'",
  37. "id": 1
  38. }' http://192.168.81.250/zabbix/api_jsonrpc.php | python -m json.tool
  39. done

3.4.执行脚本

  1. [root@k8s-master ~]# chmod a+x zabbix_host_creates.sh
  2. [root@k8s-master ~]# sh zabbix_host_creates.sh

脚本输出
zabbix api批量添加数百台监控主机 - 图2

3.5.查看监控主机是否批量创建成功

全部为有效状态
zabbix api批量添加数百台监控主机 - 图3