一、编写脚本获取端口号
脚本内容:
# cat /usr/local/zabbix-agent/scripts/tcp_port.sh
#!/bin/bash
ports=(`netstat -tnl|egrep -i "$1"|awk {'print $4'}|awk -F':' '{if ($NF~/^[0-9]*$/) print $NF}'|sort |uniq 2>/dev/null`)
length=${#ports[@]}
printf "{\n"
printf '\t'"\"data\":["
for ((i=0;i<$length;i++))
do
printf '\n\t\t{'
printf "\"{#TCP_PORT}\":\"${ports[$i]}\"}"
if [ $i -lt $[$length-1] ];then
printf ','
fi
done
printf "\n\t]\n"
printf "}\n"
脚本添加执行权限:
# chown -R zabbix:zabbix /usr/local/zabbix-agent/scripts/
# chmod 755 /usr/local/zabbix-agent/scripts/tcp_port.sh
尝试执行脚本:
# /usr/local/zabbix-agent/scripts/tcp_port.sh
{
"data":[
{"{#TCP_PORT}":"10050"},
{"{#TCP_PORT}":"10051"},
{"{#TCP_PORT}":"3306"},
{"{#TCP_PORT}":"4505"},
{"{#TCP_PORT}":"4506"},
{"{#TCP_PORT}":"7890"},
{"{#TCP_PORT}":"80"}
]
}
二、将脚本分发到Zabbix Agent
假如将脚本存放在/usr/local/zabbix-agent/scripts/目录下。需要修改Zabbix Agent配置文件,以应用该脚本:
# cat /usr/local/zabbix-agent/etc/zabbix_agentd.conf.d/tcp_port.conf
UnsafeUserParameters=1
UserParameter=tcpportlisten,/usr/local/zabbix-agent/scripts/tcp_port.sh "$1"
修改配置之后,重启Zabbix Agent服务。
三、通过zabbix_get命令测试
重启Zabbix Agent服务之后,在Zabbix Server端通过zabbix_get
命令测试能否正常获取到值:
# /usr/local/zabbix-agent/bin/zabbix_get -s 'server01' -k 'tcpportlisten'
{
"data":[
{"{#TCP_PORT}":"10050"},
{"{#TCP_PORT}":"10051"},
{"{#TCP_PORT}":"3306"},
{"{#TCP_PORT}":"4505"},
{"{#TCP_PORT}":"4506"},
{"{#TCP_PORT}":"7890"},
{"{#TCP_PORT}":"80"}
]
}
四、在Zabbix前端页面添加Discovery rule
首先选择合适的模板。例如,在自定义的名称为”Linux Template“的模板中创建发现规则:
定义自动发现规则:
为自动发现规则创建items:
为自动发现规则创建触发器:
将该模板链接到对应的主机,自动发现规则将会自动发现主机上开放的TCP端口号: