编写发现脚本

编写脚本:

vim /opt/zabbix/custom_discovery.sh

脚本内容:

#!/bin/bash
 
hostnames=(`cat /opt/zabbix/hosts | sort 2>/dev/null`)
length=${#hostnames[@]}
 
printf "{\n"
printf  '\t'"\"data\":["
for ((i=0;i<$length;i++))
do
        printf '\n\t\t{'
        printf "\"{#HOST_ADDR}\":\"${hostnames[$i]}\"}"
        if [ $i -lt $[$length-1] ];then
                printf ','
        fi
done
printf  "\n\t]\n"
printf "}\n"

测试脚本:

vim /opt/zabbix/hosts
 
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5
192.168.0.6
192.168.0.7
192.168.0.8
192.168.0.9
$ /opt/zabbix/custom_discovery.sh 
{
	"data":[
		{"{#HOST_ADDR}":"192.168.0.1"},
		{"{#HOST_ADDR}":"192.168.0.2"},
		{"{#HOST_ADDR}":"192.168.0.3"},
		{"{#HOST_ADDR}":"192.168.0.4"},
		{"{#HOST_ADDR}":"192.168.0.5"},
		{"{#HOST_ADDR}":"192.168.0.6"},
		{"{#HOST_ADDR}":"192.168.0.7"},
		{"{#HOST_ADDR}":"192.168.0.8"},
		{"{#HOST_ADDR}":"192.168.0.9"}
	]
}

创建userparameter

创建userparameter_custom_discovery.conf:

vim /etc/zabbix/zabbix_agentd.d/userparameter_custom_discovery.conf

添加如下内容:

UserParameter=custom.discovery,/opt/zabbix/custom_discovery.sh

重启zabbix-agent

systemctl restart zabbix-agent.service

测试key

# 注意使用zabbix用户执行确保有效
sudo -u zabbix zabbix_agentd -t custom.discovery

Web界面添加key

Configuration → Hosts → Select A Host → Discovery rules → Create discovery rule

添加Item prototypes

Configuration → Hosts → Select A Host → Discovery rules → Select A discovery rule → Item prototypes → Create item prototype