应用背景:
为了zabbix-agent端能自动把服务器端的服务端口汇报给 zabbix server端,监控其端口是否存活可用,
用下面的脚本:service_scan.py 部署于agent端 /usr/local/zabbix-agent/bin/service_scan.py
部署准备:
- service_scan.py脚本 依懒 python2.7版本下的 psutil库,
- 需要在agent端安装 python2.7版本,
- 用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()
原文地址:https://www.cnblogs.com/moorewqk/p/8245046.html
时间: 2024-11-10 05:39:49