zabbix的网络监控能力特别捉急
公司领导要求又高开发了这个玩意
'''
import datetime
import json
import sys
import os
import re
import subprocess
class tools(object):
def init(self):
pass
def file_read(self,filename):
filename = "/etc/zabbix/externalscripts/zabbix_mtr/%s.json" % filename
f = open(filename, 'r', encoding='utf-8')
data = json.load(f)
f.close()
return data
def file_write(self,filename,data):
filename = "/etc/zabbix/externalscripts/zabbix_mtr/%s.json" % filename
f = open(filename, 'w',encoding='utf-8')
json.dump(data, f)
f.close()
def is_file_exist(self,filename):
filename = "/etc/zabbix/externalscripts/zabbix_mtr/%s.json" % filename
return os.path.exists(filename)
class ZabbixMtr(object):
def init(self, snt=30):
self.snt = snt
self.tools = tools()
def ping(self, ipaddr):
from mass_ping import MassPing
hosts = [ipaddr, ]
ping = MassPing(hosts=hosts, thread_count=len(hosts), test_count=2)
return 1 if ping.each_ping(ipaddr) else 0
def mtr(self, ipaddr):
mtr_cmd = 'mtr -r -n -c %s %s|grep -Ev "Start:|HOST:"' % (self.snt, ipaddr)
ret = os.popen(mtr_cmd).read()
return ret
def mtr_infos(self, ipaddr):
ret = self.mtr(ipaddr)
ret = re.findall(r'[0-9.].|--(.*)', ret)
ret_dic = {}
for i in ret:
i = re.findall('([0-9.]+)', i)
if len(i) == 8:
ret_dic[i[0]] = i
return ret_dic
def mtr_info(self, ipaddr, msg, ip_route):
if ip_route == None:
ip_route = ipaddr
new_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
deadline_list = []
if self.tools.is_file_exist(ipaddr):
msg_dic = self.tools.file_read(ipaddr)
deadline = msg_dic['Time']
deadline = datetime.datetime.strptime(deadline, "%Y-%m-%d %H:%M")
deadline_list.append(deadline.strftime("%Y-%m-%d %H:%M"))
deadline = (deadline + datetime.timedelta(minutes=1)).strftime("%Y-%m-%d %H:%M")
deadline_list.append(deadline)
if new_date in deadline_list:
msg_dic = self.tools.file_read(ipaddr)
else:
info = self.mtr_infos(ipaddr)
if ip_route in info:
info = info[ip_route]
else:
info = info.popitem()[1]
msg_dic = {
"ipaddr": info[0],
"Loss": info[1],
"Snt": info[2],
"Last": info[3],
"Avg": info[4],
"Best": info[5],
"Wrst": info[6],
"StDev": info[7],
"Time": new_date,
}
self.tools.file_write(ipaddr, msg_dic)
return msg_dic[msg]
def scan_route(self, ipaddr):
info = self.mtr_infos(ipaddr)
routes = []
for k in info:
routes.append(k)
ip_route = json.dumps({'route': routes}, indent=4, separators=(',', ':'))
return ip_route
if name == 'main':
opt = sys.argv[1]
ipaddr = sys.argv[2]
ip_route = sys.argv[3]
msg = sys.argv[4]
method_dic = {
'mtr_info':'info',
'scan_route':'scan',
'ping':'ping',
}
if opt == method_dic['scan_route']:
zmtr = ZabbixMtr(1)
ret = zmtr.scan_route(ipaddr)
print(ret)
elif opt == method_dic['mtr_info']:
zmtr = ZabbixMtr(5)
ret = zmtr.mtr_info(ipaddr,msg,ip_route)
print(ret)
elif opt == method_dic['ping']:
zmtr = ZabbixMtr(1)
ret = zmtr.ping(ipaddr)
print(ret)
'''