zabbix_agent自动发现服务端口

Posted moorewqk

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了zabbix_agent自动发现服务端口相关的知识,希望对你有一定的参考价值。

应用背景:

为了zabbix-agent端能自动把服务器端的服务端口汇报给 zabbix server端,监控其端口是否存活可用,

用下面的脚本:service_scan.py   部署于agent端 /usr/local/zabbix-agent/bin/service_scan.py

部署准备:

  1. service_scan.py脚本 依懒 python2.7版本下的 psutil库,
  2. 需要在agent端安装 python2.7版本,
  3. 用python2.7 安装相关的 psutil库
  /usr/local/python27/bin/pip install psutil

  

服务器端口自动发现脚本: service_scan.py

 

#!/usr/local/python27/bin/python
# author: [email protected]
#


import os, sys, time
import commands
import psutil
import socket
import json


del_list = ["rpc.statd","java"]
def Handle_Connects():
    rows = []
    lc = psutil.net_connections(inet)
    for c in lc:
        (ip, port) = c.laddr
        if ip == 0.0.0.0 or ip == :::
            if c.type == socket.SOCK_STREAM and c.status == psutil.CONN_LISTEN:
                proto_s = tcp
            #elif c.type == socket.SOCK_DGRAM:
            #    proto_s = ‘udp‘
            else:
                continue
            pid_s = str(c.pid) if c.pid else (unknown)
            #print pid_s,port
            rows.append(%s:%s%(pid_s,port))

    dedup_list = {}.fromkeys(rows).keys()
    return dedup_list

def handler_pid(pid,port):

        service_dict = {}
        p = psutil.Process(int(pid))
        if p.as_dict()[name] == jsvc:
            service_pname = p.as_dict()[environ][HOME].split(/)[3]
            service_dict[{#PNAME}] = service_pname
            service_dict[{#PPORT}] = port
        else:
            service_pname = p.as_dict()[name]
            service_dict[{#PNAME}] = service_pname
            service_dict[{#PPORT}] = port


        return service_dict



def main():
    zb_dict = {}
    service_list = []
    result_list = []
    clist = []
    for i in Handle_Connects():
        pid = i.split(:)[0]
        port = i.split(:)[1]

        service_list.append(handler_pid(pid,port))
    for dictlist in service_list:
        if dictlist["{#PNAME}"] in  del_list:
            result_list.append(dictlist)
            #service_list.remove(dictlist)
    #print result_list
    for delname in service_list:
        if delname not in result_list:
            clist.append(delname)
    zb_dict[data] = clist
    print json.dumps(zb_dict,sort_keys=True,indent=4)


if __name__ == "__main__":
     main()

 

以上是关于zabbix_agent自动发现服务端口的主要内容,如果未能解决你的问题,请参考以下文章

zabbix实现网络发现自动注册自动监控

zabbix 自动注册和自动发现

zabbix登陆问题:cannot allocate shared memory for collector

为主机添加zabbix监控

通过zabbix自动发现Tomcat服务端口

zabbix 自动发现指定端口和服务