zabbix_agent自动发现服务端口

假如想象 提交于 2020-05-02 09:21:35

应用背景:

      zabbix监控系统介绍及安装,参考大牛运维生存时间,这儿就不啰嗦了,

为了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: moorewqk@163.com
#


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()

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!