最新消息:

zabbix端口监控-自动发现和添加监控

IT技术 ipcpu 393浏览

利用zabbix的LLD可以实现端口的自动发现和添加监控

Shell脚本如下

#!/bin/bash
portarray=(`sudo netstat -tnlp|egrep -i "$1"|awk {'print $4'}|awk -F':' '{if ($NF~/^[0-9]*$/) print $NF}'|sort|uniq`)
#namearray=(`netstat -tnlp|egrep -i "$1"|awk {'print $7'}|awk -F'/' '{if ($NF != "Address") print $NF}'|uniq`)
length=${#portarray[@]}
printf "{\n"
printf '\t'"\"data\":["
for ((i=0;i<$length;i++))
  do
     printf '\n\t\t{'
     printf "\"{#TCP_PORT}\":\"${portarray[$i]}\"}"
# printf "\"{#TCP_NAME}\":\"${namearray[$i]}\"}"
     if [ $i -lt $[$length-1] ];then
                printf ','
     fi
  done
printf "\n\t]\n"
printf "}\n"

运行效果如下

后来发现,有些端口根本就不知道是什么进程,有些混乱,于是又使用python编写了可以读取进程名称和端口的脚本,如下

#!/usr/bin/env python
#coding=utf-8
#Debug in Python2.7
#used for discovery the Listen Port and Process

import os
import json
import string

t = os.popen(""" sudo ss -tunlp |grep LISTEN |sed "s#::#FF#g" |grep users |sort |uniq """)

array = []
for port in t.readlines():
 r=port.strip()

 #print r
 port = r.split(':')[1].split(' ')[0]
        try:
     name = r.split('\"')[1]
        except:
            name = "none"

 cluster = {}
        cluster['{#TCP_PORT}'] = port
        cluster['{#TCP_NAME}'] = name

        array.append(cluster)


#amy = [{k:v} for k,v in dict([list(d.iteritems())[0] for d in array]).iteritems()] 
amy = [dict(t) for t in set([tuple(d.items()) for d in array])]

print json.dumps({'data':amy},sort_keys=True,indent=4,separators=(',',':'))

效果如下

接下来就是去zabbix系统中添加自动发现规则了。

转载请注明:IPCPU-网络之路 » zabbix端口监控-自动发现和添加监控