码迷,mamicode.com
首页 > 其他好文 > 详细

zabbix_agent自动发现服务端口

时间:2019-06-22 19:39:21      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:ret   bin   运维   pad   man   oat   __name__   table   udp   

应用背景:

      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库
1
/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自动发现服务端口

标签:ret   bin   运维   pad   man   oat   __name__   table   udp   

原文地址:https://www.cnblogs.com/jianghanyang/p/11069953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!