1、zabbix_agent端部署自定义脚本,获取运行的服务端口并将数据以json类型返回给zabbix_server
#!/usr/bin/env python
#coding:utf-8
import os,json
port_list=[]
port_dict={"data":None}
cmd='''netstat -tnlp|grep -v 127.0.0.1|egrep -i "java|php|httpd|nginx|mysqld|redis|squid3|named"|awk {'print $4'}|awk -F':' '{if ($NF~/^[0-9]*$/) print $NF}'|sort|uniq'''
local_ports=os.popen(cmd).readlines()
for port in local_ports:
pdict={}
pdict["{#TCP_PORT}"]=port.replace("\n", "")
port_list.append(pdict)
port_dict["data"]=port_list
jsonStr = json.dumps(port_dict, sort_keys=True, indent=4)
print jsonStr
使用批量管理工具ansible在zabbix_agent创建脚本目录,将python脚本拷贝至脚本目录,修改zabbix_agentd.conf添加自定义参数,修改sudoers为zabbix账号添加sudo权限,最后重启zabbix_agentd服务使配置生效:
ansible all -m file -a 'path=/usr/local/zabbix/script state=directory' ansible all -m copy -a 'src=/etc/ansible/monitor/check_port.py dest=/usr/local/zabbix/script' ansible all -m lineinfile -a "dest=/usr/local/zabbix/etc/zabbix_agentd.conf line='UserParameter=tcpportlisten,/usr/local/zabbix/script/check_port.py'" ansible all -m lineinfile -a "dest=/etc/sudoers regexp='^%zabbix' line='%zabbix ALL=(ALL) NOPASSWD: ALL' validate='visudo -cf %s'" ansible all -m service -a "name=zabbix_agentd state=restarted"
zabbix_server使用zabbix-get看能否获取数据:
zabbix_get -s 10.0.22.2 -p 10050 -k tcpportlisten { "data": [ { "{#TCP_PORT}": "53" }, { "{#TCP_PORT}": "80" } ] }
2、zabbix管理web添加自动发现规则:我配置在了默认模板Template OS Linux里
添加自动发现规则:
下图键值必须和zabbix_agent配置的键值保持一致:
添加触发器用来报警:值为0则端口不通,值为1则端口通
添加完之后等一会儿图就会生成了。