def start(self, args): self.zabbix = Zabbix(args['zabbix']) self.server = Dashboard(args['dashboard']) self.lldpctl = LldpCtl(args['discovery']) self.namespaces = args['namespaces'] self.check = args['check'] self.delay = args['delay'] # Запуск функции run из родительского класса ProcessLauncher self.run()
class ZabbixLib(object): """ """ _result = None _zb = None def __init__(self, host, port, timeout=1.0): """ """ self._zb = Zabbix(str(host), int(port), float(timeout)) def send_command(self, cmd): """ """ self._result = self._zb.send_command(cmd) def close_connection(self): """ """ self._zb.close_conn() def result_in_range(self, range_min, range_max): """ """ val = float(self._result) if val < float(range_min) or val > float(range_max): raise AssertionError('%s != (%s, %s)' % (val, range_min, range_max)) def result_should_be(self, expected): """ """ if expected != self._result: raise AssertionError('%s != %s\n' % (self._result, expected)) else: return True def test(self): """ """ self._result = self._zb.test()
def load(self, parser_args): try: # parse the supplied args with ConfigParser.parse_args self._args = self._parser.parse_args(parser_args) except IOError as e: log.error("Could not open file %s: %s" % (e.filename, e.strerror)) exit(1) if self._args.debug: log.setLevel(logging.DEBUG) log.debug("Debug enabled") self.METHOD_TYPE = getattr(self._args, 'type') self.METHOD = getattr(self._args, 'subparser_name') if self.METHOD not in ['help']: self.HOSTS = {} rets = {} for host in self._args.hosts: self.HOSTS[host] = Zabbix(host, self._args.uri_path, self._args.user, self._args.noverify, self._args.cacert, self._args.http, self._args.timeout) zapi_function = getattr( getattr(getattr(self.HOSTS[host], 'zapi'), self.METHOD_TYPE), self.METHOD) # If the listkeys argument was supplied, we need to override # args.arguments to pull one resource if getattr(self._args, 'listkeys', False): self._args.arguments = ['output=extend', 'limit=1'] # convert the arguments into the required format for the zapi # object. args_real = parse_args(self._args.arguments) # Parse specific cli arguments and update args_real args_to_parse = ['search', 'filter'] for key in args_to_parse: if getattr(self._args, key, None) is not None: args_real[key] = parse_args(getattr(self._args, key)) self.JOBS[host] = (zapi_function, args_real)
# sync configuration syncGroups = config['groups'] # define LDAP ldap = LDAP(uri=ldapUri, bind_user=ldapBindUser, bind_password=ldapBindPassword, object_group=ldapObjectGroup, object_user=ldapObjectUser, attribute_member=ldapAttributeMember, attribute_last_name=ldapAttributeLastName, attribute_first_name=ldapAttributeFirstName, attribute_username=ldapAttributeUsername) # define Zabbix zabbix = Zabbix(url=zabbixUrl, user=zabbixUser, password=zabbixPassword) users = {} # loop over configuration groups for group in syncGroups: # get group id z_group_id = zabbix.group_update_or_create( group['name'], group.get('permissions', [])) # Get ldap group members members = ldap.get_group_member(group['dn']) for member in members:
class Statistics(ProcessLauncher): def __init__(self): self.type = 'statistics' def start(self, args): self.zabbix = Zabbix(args['zabbix']) self.server = Dashboard(args['dashboard']) self.lldpctl = LldpCtl(args['discovery']) self.namespaces = args['namespaces'] self.check = args['check'] self.delay = args['delay'] # Запуск функции run из родительского класса ProcessLauncher self.run() # Отправка статистики def single(self, ns): self.signal() self.lldpctl.start() # Время на инициализацию LLDP time.sleep(5) while True: self.location = self.lldpctl.get_location() for i in self.results.keys(): res = self.results.get(i, 'NONE') if res != 'NONE': if res['type'] == 'dhcp' and res['ns'] == ns: dhcp_state = res.get('state', 'NONE') dhcp_time = res.get('time', None) if dhcp_state == 'OK' and dhcp_time > 30: dhcp_state = 'WARN' try: if dhcp_state != 'RUN': self.zabbix.send(self.location, res['type'] + '.' + res['ns'], dhcp_time) self.server.send_data({ 'location': self.location, 'service': ns, 'check' : res['check'], 'value': dhcp_state }) except Exception as e: logging.info("[Statistics] Generic exception: %s" % str(e)) elif res['type'] == 'ping' and res['ns'] == ns: ping_state = res.get('state', 'NONE') ping_max_rtt = res.get('max_rtt', None) ping_avg_rtt = res.get('avg_rtt', None) ping_min_rtt = res.get('min_rtt', None) ping_packet_lost = res.get('packet_lost', None) if ping_state == 'OK' and (ping_packet_lost != 0 or float(ping_avg_rtt) > 200): ping_state = 'WARN' try: if ping_state != 'RUN': self.zabbix.send(self.location, res['type'] + '.time.' + res['ns'] + '[' + res['check'] + ']', ping_avg_rtt) self.zabbix.send(self.location, res['type'] + '.lost.' + res['ns'] + '[' + res['check'] + ']', ping_packet_lost) self.server.send_data({ 'location': self.location, 'service': ns, 'check' : res['check'], 'value' : ping_state }) except Exception as e: logging.info("[Statistics] Generic exception: %s" % str(e)) elif res['type'] == 'dns' and res['ns'] == ns: dns_state = res.get('state', 'NONE') dns_qtime = res.get('qtime', None) if dns_state == 'OK' and float(dns_qtime) > 200: dns_state = 'WARN' try: if dns_state != 'RUN': self.zabbix.send(self.location, res['type'] + '.' + res['ns'], dns_qtime) self.server.send_data({ 'location': self.location, 'service': ns, 'check' : res['check'], 'value': dns_state }) except Exception as e: logging.info("[Statistics] Generic exception: %s" % str(e)) elif res['type'] == 'http' and res['ns'] == ns: http_state = res.get('state', 'NONE') http_code = res.get('code', None) http_time = res.get('time', None) http_speed = res.get('speed', None) http_size = res.get('size', None) if http_state == 'OK' and float(http_time) > 5: http_state = 'WARN' try: if http_state != 'RUN': self.zabbix.send(self.location, res['type'] + '.time.' + res['ns'] + '[' + res['check'] + ']', http_time) self.zabbix.send(self.location, res['type'] + '.speed.' + res['ns'] + '[' + res['check'] + ']', http_speed) self.server.send_data({ 'location': self.location, 'service': ns, 'check' : res['check'], 'value': http_state }) except Exception as e: logging.info("[Statistics] Generic exception: %s" % str(e)) elif res['type'] == 'rzs' and res['ns'] == ns: rzs_state = res.get('state', 'NONE') rzs_total = res.get('rzs_total', None) rzs_available = res.get('rzs_available', None) rzs_unavailable = res.get('rzs_unavailable', None) if rzs_state == 'OK' and (float(rzs_available)/float(rzs_total) > 0.1): rzs_state = 'WARN' if rzs_state == 'OK' and (float(rzs_available)/float(rzs_total) > 0.3): rzs_state = 'FAIL' try: if rzs_state != 'RUN': self.zabbix.send(self.location, res['type'] + '.total.' + res['ns'], rzs_total) self.zabbix.send(self.location, res['type'] + '.available.' + res['ns'], rzs_available) self.zabbix.send(self.location, res['type'] + '.unavailable.' + res['ns'], rzs_unavailable) self.server.send_data({ 'location': self.location, 'service': ns, 'check' : res['check'], 'value': rzs_state }) except Exception as e: logging.info("[Statistics] Generic exception: %s" % str(e)) time.sleep(float(self.delay))
def main(args=None): parser = build_parsers(version=__version__) if args is None: try: args = parser.parse_args(sys.argv[1:]) except IOError as e: log.error("Could not open file %s: %s" % (e.filename, e.strerror)) exit(1) if args.debug: log.setLevel(logging.DEBUG) log.debug("Debug enabled") method_type = getattr(args, 'type') method = getattr(args, 'subparser_name') if method not in ['help']: Z = {} rets = {} for host in args.hosts: count = 0 Z[host] = Zabbix(host, args.uri_path, args.user, args.noverify, args.cacert, args.http, args.timeout) # allow the user to auth 3 times before returning an error while count < 3 and Z[host].zapi.auth == '': try: Z[host].auth(args.user, getpass.getpass()) # if successful, break out of the loop break except ZabbixNotAuthorized: pass count = count + 1 if Z[host].zapi.auth == '': log.exception(ZabbixNotAuthorized('Invalid username or password')) func = getattr( getattr(getattr(Z[host], 'zapi'), method_type), method) # If the listkeys argument was supplied, we need to override # args.arguments to pull one resource if args.listkeys: args.arguments = ['output=extend', 'limit=1'] args_real = parse_args(args.arguments) if type(args_real) == str or type(args_real) == int: rets[host] = func(str(args_real)) elif type(args_real) == list: rets[host] = func(*args_real) else: rets[host] = func(**args_real) final = [] for ret in rets: # if the results are not a list, the final output should be final # this was added to support the configuration.export method of the # API if type(rets[ret]) == list: final += rets[ret] elif type(rets[ret]) == dict: final = rets[ret] else: final = eval(rets[ret]) if any(method_type in s for s in ['alert']): final = sorted(final, key=lambda k: k['clock']) # If there is a timestamp we want to do stuff to it if method not in ['create', 'delete', 'update', 'export']: # Check if one of the following keys exist list_of_checks = ['clock', 'lastchange'] matched_check = None for check in list_of_checks: try: if final[0].get(check, None): matched_check = check except IndexError: pass else: matched_check = None # If a key exists, then sort on that key and update the unix_timestamp # to readable format if matched_check: final = sorted(final, key=lambda k: k[matched_check]) for item in final: item[matched_check] = str( datetime.fromtimestamp(float(item[matched_check]))) # if the "listkeys" argument was supplied, we should return the # keys of the first resource in the list. if args.listkeys: sys.stdout.write(json.dumps(final[0].keys(), indent=2)) else: sys.stdout.write(json.dumps(final, indent=2)) else: log.info( 'https://www.zabbix.com/documentation/2.2/manual/api/reference/{0}'.format(method_type))
from WeChat import WeChat import os,sys,thread,time if __name__ == '__main__': db = SQLiteDB db.CreatTable() z = Zabbix() #zabbix类 w = WeChat() #wechat类 th = [] z.Zabbix_Address = '' z.Zabbix_Username = '' z.Passwd = '' z.z_Intervals = 600 #zabbix告警入库间隔 z.w_Intervals = 3600 #wechat告警入库间隔 z.sleeptime = 10 #Zabbix心跳间隔 w.Intervals = 3 #告警检测心跳间隔 w.xintiao = 2 #微信心跳间隔 z.get_auth() #zabbix token
def __init__(self, host, port, timeout=1.0): """ """ self._zb = Zabbix(str(host), int(port), float(timeout))