首页 > 其他 > 详细

zabbix_agent自动发现服务端口

时间:2018-01-08 22:16:24      阅读:254      评论:0      收藏:0      [点我收藏+]

应用背景:

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

 

zabbix_agent自动发现服务端口

原文:https://www.cnblogs.com/moorewqk/p/8245046.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!