def main(zabbix, user, password, host):
    zapi = ZabbixAPI(url=zabbix,
                     user=user, password=password)

    host_id = zapi.get_id(item_type='host', item=host)
    if host_id is None:
        create_zabbix_host(zapi=zapi, host=host)
    else:
        update_zabbix_host(zapi=zapi, host=host, host_id=host_id)
class ZabbixTemplates:
    def __init__(self, _url, _user, _password):
        self.zapi = ZabbixAPI(url=_url, user=_user, password=_password)

    def exportTemplates(self, args):
        request_args = {"output": "extend"}

        if args.templates != 'All':
            request_args.filter = {"host": [args.tempaltes]}

        result = self.zapi.do_request('template.get', request_args)
        if not result['result']:
            print "No matching host found for '{}'".format(hostname)
            exit(-3)

        if result['result']:
            for t in result['result']:
                dest = args.out_dir + '/' + t['host'] + '.xml'
                self.exportTemplate(t['templateid'], dest)

    def exportTemplate(self, tid, oput):

        print "tempalteid:", tid, " output:", oput
        args = {"options": {"templates": [tid]}, "format": "xml"}

        result = self.zapi.do_request('configuration.export', args)
        template = xml.dom.minidom.parseString(
            result['result'].encode('utf-8'))
        date = template.getElementsByTagName("date")[0]
        # We are backing these up to git, steralize date so it doesn't appear to change
        # each time we export the templates
        date.firstChild.replaceWholeText('2016-01-01T01:01:01Z')
        f = open(oput, 'w+')
        f.write(template.toprettyxml().encode('utf-8'))
        f.close()
示例#3
0
class ZabbixTemplates:
    def __init__(self, _url, _user, _password):
        self.zapi = ZabbixAPI(url=_url, user=_user, password=_password)

    def exportTemplates(self, args):
        request_args = {"output": "extend"}

        if args.templates != 'All':
            request_args.filter = {"host": [args.tempaltes]}

        result = self.zapi.do_request('template.get', request_args)
        if not result['result']:
            print "No matching host found for '{}'".format(hostname)
            exit(-3)

        if result['result']:
            for t in result['result']:
                dest = args.out_dir + '/' + t['host'] + '.json'
                self.exportTemplate(t['templateid'], dest)

    def exportTemplate(self, tid, oput):

        print "tempalteid:", tid, " output:", oput
        args = {"options": {"templates": [tid]}, "format": "json"}

        result = self.zapi.do_request('configuration.export', args)
        jsondump = json.dumps(result['result'])
        template = json.loads(jsondump)

        f = open(oput, 'w+')
        f.write(template)
        f.close()
示例#4
0
    def connect(self):
        """
		Metodo para conexao ao Zabbix via API
		"""
        self.zapi = ZabbixAPI(url=self._server_url,
                              user=self._user,
                              password=self._password)
        self._log.logger.debug("Conectou na API Zabbix.")
示例#5
0
def main(zabbix, user, password, host):
    zapi = ZabbixAPI(url=zabbix, user=user, password=password)

    host_id = zapi.get_id(item_type='host', item=host)
    if host_id is None:
        create_zabbix_host(zapi=zapi, host=host)
    else:
        update_zabbix_host(zapi=zapi, host=host, host_id=host_id)
示例#6
0
    def __init__(self, _url, _user, _password):
        url = _url
        user = _user
        password = _password

        try:
            self.zapi = ZabbixAPI(url=url, user=user, password=password)
        except Exception as e:
            print 'Error in creating connection to Zabbix Api (%s)' % (url)
            raise Exception(e)

        self.metric_names_regex = [
            '^(?P<metric_name>ICMP loss).*',
            '^(?P<metric_name>ICMP ping).*',
            '^(?P<metric_name>ICMP response time).*',
            '^(?P<metric_name>Incoming traffic) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Outgoing traffic) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>In utilization) on (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Out utilization) on (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Inbound errors) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Outbound errors) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Percentage inbound errors) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Percentage outbound errors) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Incoming unicast packets) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Outcoming unicast packets) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Admin status) of interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*'
            ### ip sla pattern 1
            ,
            '^(?P<metric_name>Jitter) for CORP-.* (?:IBM-(?P<tos1>0)-|1-(?P<tos>0)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.* (?:IBM-(?P<tos1>0)-|1-(?P<tos>0)-).*',
            '^(?P<metric_name>Packet loss) for CORP.* (?:IBM-(?P<tos1>0)-|1-(?P<tos>0)-).*',
            '^(?P<metric_name>Jitter) for CORP-.* (?:IBM-(?P<tos1>96)-|1-(?P<tos>96)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.* (?:IBM-(?P<tos1>96)-|1-(?P<tos>96)-).*',
            '^(?P<metric_name>Packet loss) for CORP.* (?:IBM-(?P<tos1>96)-|1-(?P<tos>96)-).*',
            '^(?P<metric_name>Jitter) for CORP-.* (?:IBM-(?P<tos1>128)-|1-(?P<tos>128)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.* (?:IBM-(?P<tos1>128)-|1-(?P<tos>128)-).*',
            '^(?P<metric_name>Packet loss) for CORP.* (?:IBM-(?P<tos1>128)-|1-(?P<tos>128)-).*',
            '^(?P<metric_name>Jitter) for CORP-.* (?:IBM-(?P<tos1>184)-|1-(?P<tos>184)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.* (?:IBM-(?P<tos1>184)-|1-(?P<tos>184)-).*',
            '^(?P<metric_name>Packet loss) for CORP.* (?:IBM-(?P<tos1>184)-|1-(?P<tos>184)-).*'
            ### ip sla pattern 2
            ,
            '^(?P<metric_name>Jitter) for CORP-.*(?:IBM-(?P<tos1>0)-|-(?P<tos>0)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.*(?:IBM-(?P<tos1>0)-|-(?P<tos>0)-).*',
            '^(?P<metric_name>Packet loss) for CORP.*(?:IBM-(?P<tos1>0)-|-(?P<tos>0)-).*',
            '^(?P<metric_name>Jitter) for CORP-.*(?:IBM-(?P<tos1>96)-|-(?P<tos>96)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.*(?:IBM-(?P<tos1>96)-|-(?P<tos>96)-).*',
            '^(?P<metric_name>Packet loss) for CORP.*(?:IBM-(?P<tos1>96)-|-(?P<tos>96)-).*',
            '^(?P<metric_name>Jitter) for CORP-.*(?:IBM-(?P<tos1>128)-|-(?P<tos>128)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.*(?:IBM-(?P<tos1>128)-|-(?P<tos>128)-).*',
            '^(?P<metric_name>Packet loss) for CORP.*(?:IBM-(?P<tos1>128)-|-(?P<tos>128)-).*',
            '^(?P<metric_name>Jitter) for CORP-.*(?:IBM-(?P<tos1>184)-|-(?P<tos>184)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.*(?:IBM-(?P<tos1>184)-|-(?P<tos>184)-).*',
            '^(?P<metric_name>Packet loss) for CORP.*(?:IBM-(?P<tos1>184)-|-(?P<tos>184)-).*'
        ]
示例#7
0
    def __init__(self, template=None):
        ZabbixCLIArguments.__init__(self)
        self._configureLogging()
        log.debug('Parser arguments: %s', self.args)

        # if no arguments, jsut print help
        if len(sys.argv) <= 1:
            self.argparser.print_help()
            sys.exit()

        if not self.args.get('template'):
            sys.exit('Template should be specified.')

        self.url = self.args['server']
        try:
            self.zapi = ZabbixAPI(
                self.url,
                user=self.args['user'],
                password=self.args['pass'])
        except:
            log.error('Error while trying open connection to zabbix server: %s',
                    self.url)

        # If we need to delete an object and exit
        if self.args.get('delete'):
            template_id = self.zapi.get_id('template', self.args['delete'][1])
            if ZabbixObject(self.zapi,
                            {'name': self.args['delete'][2]},
                            template_id=template_id,
                            obj_type=self.args['delete'][0]).delete():
                log.info(
                    '"{2}" {0} was deleted from "{1}"'.format(
                        *self.args['delete']))
            else:
                log.exit(
                    'Error while trying to delete: "{2}" {0} from "{1}"'.format(
                        *self.args['delete']))
            exit()

        # Set template name from __init__ params or args
        if template:
            self.template_name = template
        else:
            self.template_name = self.args.get('template')

        # Load template from file
        self.template = ZabbixTemplateFile(self.template_name, templates_dir=self.args.get('templates_dir'))
        self.template_id = None

        # When template loaded, set defaults and run apply process
        if self.template:
            self.config = ZabbixDefaults()
            self.apply()
示例#8
0
def main():
    global config
    global zapi
    config = configParse(config_file)
    config.parse()
    zapi = ZabbixAPI(url=config.zabbix_url,
                     user=config.zabbix_user,
                     password=config.zabbix_passwd)
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('-c',
                        '--create-host',
                        help='Provide host name if you need create host')
    parser.add_argument('-p',
                        '--host-port',
                        default='10050',
                        help='Provide host port if you need create host')
    parser.add_argument('-i',
                        '--host-ip',
                        help='Provide host ip if you need create host')
    args = parser.parse_args()
    if args.create_host:
        createHost(hostName=args.create_host,
                   hostIP=args.host_ip,
                   hostPort=args.host_port,
                   groupID='347',
                   templateID='10068')
    else:
        print "Warning: Check your parameters!"
        sys.exit(1)
def main():
    (options, _) = get_options()

    try:
        client = ZabbixAPI(url=options.z_url,
                           user=options.z_userid,
                           password=options.z_passwd)
    except URLError as e:
        sys.exit('Failed to connect Zabbix server (%s)' % e)
    except ZabbixAPIException as e:
        sys.exit('Failed to authenticate Zabbix (%s)' % e)

    # get ID of MediaType for StackStorm if it exists, or None.
    mediatype_id = is_already_registered_mediatype(client, options)

    # register a new MediaType or update one which is already registered to dispatch events
    # to the StackStorm
    mediatype_id = register_media_type(client, options, mediatype_id)

    # get ID of Action for StackStorm if it exists, or None.
    action_id = is_already_registered_action(client, options)

    # register a Action which is associated with the registered MediaType
    register_action(client, mediatype_id, options, action_id)

    # register a Media to the Admin user
    register_media_to_admin(client, mediatype_id, options)

    print('Success to register the configurations for StackStorm to the Zabbix Server.')
def main(argv):

    # Parse arguments and build work variables
    args = ArgumentParser()
    zabbixURL = args.Z
    zabbixUsername = args.u
    zabbixPassword = args.p
    hostName = args.H
    macroName = args.M

    # API Connect
    print('Connecting to {}'.format(zabbixURL))
    zapi = ZabbixAPI(url=zabbixURL,
                     user=zabbixUsername,
                     password=zabbixPassword)

    hostObj = zapi.host.get(search={'host': hostName}, output='hostids')
    print('Host {} (Id: {})'.format(hostName, hostObj[0]['hostid']))

    currentMacro = zapi.usermacro.get(hostids=hostObj[0]['hostid'],
                                      filter={'macro': macroName})

    if (currentMacro):
        newMacroValue = random.randint(1, 1001)
        print('{}: current value "{}" -> new value "{}"'.format(
            macroName, currentMacro[0]['value'], newMacroValue))
        zapi.usermacro.update(hostmacroid=currentMacro[0]['hostmacroid'],
                              value=newMacroValue)
    else:
        print('No {} macro found on host {}'.format(macroName, hostName))
def main(argv):

    # Parse arguments and build work variables
    args = ArgumentParser()
    zabbixURL = args.Z
    zabbixUsername = args.u
    zabbixPassword = args.p
    hostNameFilter = args.f

    zapi = ZabbixAPI(url=zabbixURL,
                     user=zabbixUsername,
                     password=zabbixPassword)

    if (hostNameFilter):
        # Filter based on the cmdline argument
        f = {'host': hostNameFilter}
        hosts = zapi.host.get(search=f, output='extend', selectTags='extend')
    else:
        hosts = zapi.host.get(output='extend')

    if (args.e):
        jsonPrint(hosts)
    else:
        for host in hosts:
            print("ID: {} - Host: {}".format(host['hostid'], host['host']))
示例#12
0
def check_stat(hostlist):
    print hostlist
    zapi = ZabbixAPI(url=environ['ZABBIX_URL'],
                     user=environ['ZABBIX_USER'],
                     password=environ['ZABBIX_PASSWORD'])
    status = "green"
    for host in hostlist:
        result = zapi.do_request('trigger.get', {
            'active': 1,
            'only_true': 1,
            'hostids': host
        })['result']
        for x in xrange(len(result)):
            if int(result[x]['priority']) > 3:
                status = "red"
    return status
def main(argv):
    # Parse arguments and build work variables
    args = ArgumentParser()
    zabbixURL = args.Z
    zabbixUsername = args.u
    zabbixPassword = args.p
    hostNameFilter = args.f

    interfaceType = {
        '1': 'agent',
        '2': 'SNMP',
        '3': 'IPMI',
        '4': 'JMX',
    }

    bulkStatus = {
        '0': 'OFF',
        '1': 'ON',
    }

    zapi = ZabbixAPI(url=zabbixURL, user=zabbixUsername,
                     password=zabbixPassword)

    if (hostNameFilter):
        # Filter based on the cmdline argument
        f = {'host': hostNameFilter}
        hosts = zapi.host.get(search=f, output='extend', selectTags='extend')
        interfaces = zapi.hostinterface.get(hostids=hosts[0]['hostid'])
    else:
        interfaces = zapi.hostinterface.get()

    for interface in (interfaces):
        print('HostID: {} - IP: {} - Type: {} - Bulk: {}'.format(
            interface['hostid'], interface['ip'], interfaceType[interface['type']], bulkStatus[interface['bulk']]))
示例#14
0
def main():
    handler = logging.StreamHandler(sys.stderr)
    LOG = logging.getLogger()
    LOG.addHandler(handler)

    options = get_options()

    LOG.setLevel(logging.DEBUG if options.debug else logging.INFO)

    zapi = ZabbixAPI(server=options.server)

    try:
        json_data = (json.load(open(options.file, "r"))
                     if options.file else json.loads(options.expression))
        zapi.login(options.username, options.password)
    except Exception as e:
        die(str(e))

    def execute_command(js):
        try:
            cls, method = js["method"].split(".", 1)
        except:
            print >> sys.stderr, "missing method name"
            return False
        try:
            obj = getattr(zapi, cls)
        except:
            print >> sys.stderr, "class %s not found" % cls
            return False
        try:
            print json.dumps(
                getattr(obj, method)(js.get("params", {})),
                **({
                    "indent": 4
                } if options.indent else {}))
        except Exception as e:
            print >> sys.stderr, str(e)
            return False
        return True

    if isinstance(json_data, list):
        for i in json_data:
            if not (execute_command(i) or options.keep_going):
                sys.exit(1)
    else:
        if not execute_command(json_data):
            sys.exit(1)
示例#15
0
def zbx_call(method, args):
    zapi = ZabbixAPI(url=settings.ZABBIX_URL, user=settings.ZABBIX_USER, password=settings.ZABBIX_PASSWD)
    args = args.replace("'", '"')
    args = json.loads(args)
    if method == "service.get" and args.get("serviceids"):
        key = ""
        for srv_id in args["serviceids"]:
            key += srv_id
        cached = cache.get(key)
        if cached:
            return cached
        else:
            result = zapi.do_request(method, args)
            cache.set(key, result, None)
            return result
    result = zapi.do_request(method, args)
    return result
示例#16
0
def main():
    handler = logging.StreamHandler(sys.stderr)
    LOG = logging.getLogger()
    LOG.addHandler(handler)

    options = get_options()

    LOG.setLevel(logging.DEBUG if options.debug else logging.INFO)

    zapi = ZabbixAPI(server=options.server)

    try:
        json_data = (json.load(open(options.file, "r")) if options.file
                     else json.loads(options.expression))
        zapi.login(options.username, options.password)
    except Exception as e:
        die(str(e))

    def execute_command(js):
        try:
            cls, method = js["method"].split(".", 1)
        except:
            print >> sys.stderr, "missing method name"
            return False
        try:
            obj = getattr(zapi, cls)
        except:
            print >> sys.stderr, "class %s not found" % cls
            return False
        try:
            print json.dumps(
                getattr(obj, method)(js.get("params", {})),
                **({"indent": 4} if options.indent else {}))
        except Exception as e:
            print >> sys.stderr, str(e)
            return False
        return True

    if isinstance(json_data, list):
        for i in json_data:
            if not (execute_command(i) or options.keep_going):
                sys.exit(1)
    else:
        if not execute_command(json_data):
            sys.exit(1)
示例#17
0
    def run(self, api_method, token, **params):
        # Initialize client object to connect Zabbix server
        if token:
            self.client = ZabbixAPI(url=self.config['zabbix']['url'])
            self.auth = token
        else:
            self.connect()

        return self._call_api_method(self.client, api_method, params)
示例#18
0
def zbx_call(method, args):
    zapi = ZabbixAPI(url=settings.ZABBIX_URL,
                     user=settings.ZABBIX_USER,
                     password=settings.ZABBIX_PASSWD)
    args = args.replace("'", "\"")
    args = json.loads(args)
    if method == "service.get" and args.get('serviceids'):
        key = ""
        for srv_id in args['serviceids']:
            key += srv_id
        cached = cache.get(key)
        if cached:
            return cached
        else:
            result = zapi.do_request(method, args)
            cache.set(key, result, None)
            return result
    result = zapi.do_request(method, args)
    return result
示例#19
0
 def connect(self):
     try:
         self.client = ZabbixAPI(url=self.config['zabbix']['url'],
                                 user=self.config['zabbix']['username'],
                                 password=self.config['zabbix']['password'])
     except ZabbixAPIException as e:
         raise ZabbixAPIException("Failed to authenticate with Zabbix (%s)" % str(e))
     except URLError as e:
         raise URLError("Failed to connect to Zabbix Server (%s)" % str(e))
     except KeyError:
         raise KeyError("Configuration for Zabbix pack is not set yet")
示例#20
0
def main(argv):

    # Parse arguments and build work variables
    args = ArgumentParser()
    zabbixURL = args.Z
    zabbixUsername = args.u
    zabbixPassword = args.p

    zapi = ZabbixAPI(url=zabbixURL,
                     user=zabbixUsername,
                     password=zabbixPassword)

    params = []
    for triggerid in args.i.split(' '):
        trigObj = {"triggerid": triggerid, "status": args.s}
        params.append(trigObj)

    # Call request directly for the custom param field, instead of using zapi.trigger.update
    result = zapi.do_request('trigger.update', params=params)
    jsonPrint(result)
示例#21
0
class zabbix_data:
    __zapi = ''

    def __init__(self):
        conf = app_config()
        config_value = conf.get_config_value()
        self.__zapi = ZabbixAPI(url=config_value['zabbix_api_addr'][0],
                                user=config_value['zabbix_api_user'][0],
                                password=config_value['zabbix_api_user'][1])

    def host_trigger_get(self, params):
        warn = []
        disable = []
        enable = []
        result = self.__zapi.do_request('host.get', params)['result']
        for i in range(len(result)):
            result[i]['triggers'] = list(
                filter(lambda x: x['value'] == "1" and x['status'] == "0",
                       result[i]['triggers']))
            if result[i]['status'] == '1':
                disable.append(result[i])
            elif result[i]['triggers']:
                warn.append(result[i])
            else:
                enable.append(result[i])
        return warn + enable + disable

    def item_history_get(self, params):
        result = self.__zapi.do_request("history.get", params)["result"]
        return result

    def host_item_get(self, params):
        result = self.__zapi.do_request("host.get", params)["result"]
        return result

    def item_get(self, params):
        result = self.__zapi.do_request("item.get", params)["result"]
        return result
示例#22
0
    def loginAPI(self, urlZB, userZB, passZB, groupHost, itemZB, rangeDay,
                 adressDB, dbName, userDB, passDB, tblName):

        # Header API
        ZABIX_ROOT = urlZB
        url = ZABIX_ROOT + '/api_jsonrpc.php'

        payload = {
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
                'user': userZB,
                'password': passZB,
            },
            "auth": None,
            "id": 0,
        }

        headers = {
            'content-type': 'application/json',
        }

        try:

            # Method use API
            zapi = ZabbixAPI(url=urlZB, user=userZB, password=passZB)
            # Test connection with API
            requestZB = requests.post(url,
                                      data=json.dumps(payload),
                                      headers=headers)
            resultZB = requestZB.json()
            json.dumps(resultZB)

            print("[INFO] API connected")
            print("[INFO] jsonrpc: {} && result: {}".format(
                resultZB['jsonrpc'], resultZB['result']))

            sendConnection = exportDataAPIzabbix()
            return sendConnection.collectAPI(zapi, groupHost, itemZB, rangeDay,
                                             adressDB, dbName, userDB, passDB,
                                             tblName)

        except Exception as e:

            print("[ALERT] API not connected")
            print("[ALERT] Zabbix URL Error: {}".format(e))
            print(
                "***********************************************************************************"
            )
            sys.exit()
示例#23
0
    def run(self, api_method, token, **params):
        # Initialize client object to connect Zabbix server

        if token:
            self.client = ZabbixAPI(url=self.config['zabbix']['url'])
            self.auth = token
        else:
            self.connect()

        return self._call_api_method(
            self.client, api_method,
            {k: v
             for k, v in params.items()
             if v is not None})  # dont include param where v=None
示例#24
0
    def run(self,
            name,
            groups,
            ipaddrs=[],
            domains=[],
            proxy_host=None,
            token=None,
            main_if=''):
        # Initialize client object to connect Zabbix server
        if token:
            self.client = ZabbixAPI(url=self.config['zabbix']['url'])
            self.auth = token
        else:
            self.connect()

        # retrieve hostgroup-ids to be set to creating host object
        hostgroups = [
            x['groupid']
            for x in self.client.hostgroup.get(filter={'name': groups})
        ]

        # make interface configurations to be set to creating host object
        interfaces = (self.get_interface_config_with_ipaddr(ipaddrs, main_if) +
                      self.get_interface_config_with_domain(domains, main_if))

        # Zabbix server requires one interface value at least
        if not interfaces:
            return (False,
                    "You have to IP address or domain value at least one.")

        # If there is no main interface, set it for the first one.
        if not any([x['main'] > 0 for x in interfaces]):
            interfaces[0]['main'] = 1

        # register a host object
        new_host = self.client.host.create(
            **{
                'host': name,
                'groups': [{
                    'groupid': x
                } for x in hostgroups],
                'interfaces': interfaces,
            })

        # register ZabbixProxy if it is necessary
        if proxy_host:
            self.set_proxy_for_host(proxy_host, new_host['hostids'])

        return (True, new_host)
示例#25
0
def list_hosts():
    zbx_host = sys.argv[1]
    zbx_user = sys.argv[2]
    zbx_pass = sys.argv[3]
    zbx_filter = sys.argv[4]
    zbx_filter_value = sys.argv[5]
    zbx_psk_identity = sys.argv[6]
    zbx_psk = sys.argv[7]

    zapi = ZabbixAPI(url=zbx_host, user=zbx_user, password=zbx_pass)
    if zbx_filter == 'host':
        res1 = zapi.do_request('host.get', {
            'search': {
                'host': zbx_filter_value
            },
            'output': ['hostid', 'name']
        })
        hosts = res1.get(u'result')
    if zbx_filter == 'template':
        res1 = zapi.do_request(
            'template.get', {
                'filter': {
                    'host': zbx_filter_value
                },
                'selectHosts': 'extend',
                'output': ['hostid', 'name']
            })
        hosts = res1.get(u'result')[0].get(u'hosts')
    if zbx_filter == 'proxy':
        res1 = zapi.do_request(
            'proxy.get', {
                'filter': {
                    'host': zbx_filter_value
                },
                'selectHosts': 'extend',
                'output': ['hostid', 'name']
            })
        hosts = res1.get(u'result')[0].get(u'hosts')
    if zbx_filter == 'host' or zbx_filter == 'template' or zbx_filter == 'proxy':
        print('Following hosts will be updated:')
        for host in hosts:
            print(host.get(u'name'))
        zapi.do_request(
            'host.massupdate', {
                'hosts': hosts,
                'tls_connect': 2,
                'tls_accept': 2,
                'tls_psk_identity': zbx_psk_identity,
                'tls_psk': zbx_psk
            })
示例#26
0
def main():
    global config
    global zapi
    config = configParse(config_file)
    config.parse()
    zapi = ZabbixAPI(url=config.zabbix_url,
                     user=config.zabbix_user,
                     password=config.zabbix_passwd)
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('-l',
                        '--link-template',
                        help='Provide template name if you need link template')
    parser.add_argument('-H',
                        '--host-name',
                        help='Provides hostname to link template')
    args = parser.parse_args()
    if args.link_template:
        linkTemplate(hostName=args.host_name, templateName=args.link_template)
    else:
        print "Warning: Check your parameters!"
        sys.exit(1)
示例#27
0
def main():

    if sys.argv[1] == '-l':

        cf = CloudFlare.CloudFlare(email=cloudflare_user,
                                   token=cloudflare_token)
        zone = sys.argv[2]
        data_t = get_status(zone, cf)
        data_to_print = zabbix_discovery_rule(data_t)
        print(data_to_print)

        store_item_values(data_t, zone)

    elif sys.argv[1] == '-s':

        zone_name = sys.argv[2]
        status_key = sys.argv[3]
        statuscodes = get_item_values(zone_name, status_key)
        print(statuscodes)

    elif sys.argv[1] == '--create':

        zapi = ZabbixAPI(url=zabbix_url,
                         user=zabbix_user,
                         password=zabbix_password)
        id = create_hostgroup(zapi)

        for host in zabbix_hosts:

            try:
                stout = create_host(host, id, zapi)
                print(stout)

            except:
                error1 = 'Host ' + host + ' ya existe en la base de datos.'
                print(error1)

    else:

        print('Parametro invalido')
示例#28
0
def main(argv):

    # Parse arguments and build work variables
    args = ArgumentParser()
    zabbixURL = args.Z
    zabbixUsername = args.u
    zabbixPassword = args.p
    hostName = args.H
    zabbixSearch = {'name': hostName}

    # API Connect
    print('Connecting to {}'.format(zabbixURL))
    try:
        zapi = ZabbixAPI(url=zabbixURL,
                         user=zabbixUsername,
                         password=zabbixPassword)
    except Exception as e:
        print("Connection error:{}".format(str(e)))
        exit()

    try:
        hosts = zapi.host.get(search=zabbixSearch,
                              output=['hostids', 'host', 'name'])
    except Exception as e:
        print("Host get error:{}".format(str(e)))
        exit()

    if (len(hosts) == 0):
        print("Can't find host {}".format(hostName))
        exit()

    for host in hosts:
        items = zapi.item.get(hostids=host['hostid'])
        for item in items:
            print(
                "HostID: {} - Host: {} ({}) - ItemID: {} - Item name: {} - Key: {}"
                .format(host['hostid'], host['name'], host['host'],
                        item['itemid'], item['name'], item['key_']))
示例#29
0
def main(argv):

    # Parse arguments and build work variables
    args = ArgumentParser()
    zabbixURL = args.Z
    zabbixUsername = args.u
    zabbixPassword = args.p
    triggerNameFilter = args.t

    zapi = ZabbixAPI(url=zabbixURL,
                     user=zabbixUsername,
                     password=zabbixPassword)

    f = {'description': triggerNameFilter}
    triggers = zapi.trigger.get(search=f, output='extend', selectTags='extend')

    if (args.e):
        jsonPrint(triggers)
    else:
        for trigger in triggers:
            print("ID: {} - Status: {} - Trigger: {}".format(
                trigger['triggerid'], trigger['status'],
                trigger['description']))
示例#30
0
import logging
from zabbix.api import ZabbixAPI

logging.basicConfig(level = logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logger = logging.getLogger(__name__)

z = ZabbixAPI(url='https://localhost/zabbix/', user='******', password='******')

t1 = z.host.getobjects(status=1})
t2 = z.do_request('host.getobjects', {'status':1})

[host['host'] for host in t1]
[host['host'] for host in t2['result']]
def main():
    parser = ArgumentParser()
    parser.add_argument("-z", "--zabbix",
                        help="Zabbox URL",
                        required=True)
    parser.add_argument("-u", "--user",
                        help="Zabbix user name",
                        required=True)
    parser.add_argument("-p", "--password",
                        help="Zabbix user password",
                        required=True)
    parser.add_argument("-D", "--dir",
                        help="Directory where charts will be saved",
                        required=True)
    parser.add_argument("-s", "--start_time",
                        help="Chart data start time",
                        required=True)
    parser.add_argument("-d", "--duration",
                        help="Chart data duration",
                        required=True)
    parser.add_argument("-H", "--host",
                        help="Host name",
                        required=True)
    args = parser.parse_args()
    zabbix = args.zabbix
    user = args.user
    password = args.password
    host = args.host
    start_time = args.start_time
    duration = int(args.duration)
    chart_dir = args.dir

    if duration < 60:
        duration = 60

    zapi = ZabbixAPI(url=zabbix,
                     user=user, password=password)

    host_id = zapi.get_id(item_type='host', item=host)

    zapi = ZabbixAPI(url=zabbix,
                     user=user, password=password)
    graphs = zapi.do_request(method="graph.get",
                             params={"hostids": host_id})['result']

    graph_ids = {}
    for graph in graphs:
        if graph['name'] in GRAPH_NAMES:
            graph_ids[graph['graphid']] = graph['name']

    s = requests.Session()
    payload = {'name': user,
               'password': password,
               'enter': 'Sign in',
               'autologin': '******',
               'request': ''}
    url = "{0}/index.php?login=1".format(zabbix)
    s.post(url, data=payload)
    for graph_id, graph_name in graph_ids.iteritems():
        url = ("{0}/chart2.php?"
               "graphid={1}&stime={2}&period={3}".format(zabbix,
                                                         graph_id,
                                                         start_time,
                                                         duration))
        response = s.get(url, stream=True)
        file_name = "{0}/{1}-{2}.png".format(chart_dir,
                                             host,
                                             graph_name.replace(" ", "_"))
        with open(file_name, 'wb') as f:
            shutil.copyfileobj(response.raw, f)
 def login(self):
     return ZabbixAPI(url=self.config['zabbix']['url'],
                      user=self.config['zabbix']['username'],
                      password=self.config['zabbix']['password'])
示例#33
0
  print("Overriding default behavior, going to truncate all original hostgroups")
  

# simple parse for arguments
url = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]
zhost = sys.argv[4]
csvHostGroups = sys.argv[5]
print "Going to connect to {} as {}".format(url,user)
print ("Will try to update zabbix hostgroups for {} with groups: {}".format(zhost,csvHostGroups))


# Create ZabbixAPI class instance
use_older_authenticate_method = False
zapi = ZabbixAPI(url, use_older_authenticate_method, user, password)

zversion = zapi.do_request('apiinfo.version')
print "Zabbix API version: {}".format(zversion['result'])


# first need to resolve the list of hostgroup names to proper ids
candidateGroupIds=[]
candidateGroups=csvHostGroups.split(",")
for candidateGroup in candidateGroups:
  print("Trying to resolve hostgroup: {}".format(candidateGroup))
  hostgroupResults = zapi.do_request('hostgroup.get', {'filter': { 'name': [ candidateGroup ]  } })
  #print("result {}, count {}".format( hostgroupResults['result'], len(hostgroupResults['result'])  ))
  if len(hostgroupResults['result'])==0:
    print("ERROR could not resolve hostgroup to id, does not exist")
    exit(2)
"""
Move hosts to a specific hostgroup list basing on a csv file
Please refer to README.md for hosts.csv syntax

"""

import csv
import json
from zabbix.api import ZabbixAPI

fileName = 'hosts.csv'
zabbixServer = 'http://yourserver/zabbix/'
zabbixUser = '******'
zabbixPass = '******'

zapi = ZabbixAPI(url=zabbixServer, user=zabbixUser, password=zabbixPass)

# Read CSV file
hostFile = open(fileName)
hostReader = csv.reader(hostFile, delimiter=';', quotechar='|')
# Uncomment if your csv has headers
#headers = hostReader.next()
hostData = list(hostReader)

# CSV Parsing
for host in hostData:
    wantedGroups = []
    actualGroupIds = []
    hostName = host[1].split("-")[0]
    moveHost = False
    consul_kv = get_kv("cloudconductor/system_domain", ret_url_encode(os.environ['CONSUL_SECRET_KEY']))
    decode_consul_kv = json.loads(consul_kv)
    decode_user_attribute = json.loads(base64.b64decode(decode_consul_kv[0]["Value"]))

    try:
        system_domain = decode_user_attribute['dns']
    except Exception as w:
        system_domain = 'localhost'
        print w, 'Please dns name change the settings as soon as possible.'

    system_name = decode_user_attribute['name']

    # Create ZabbixAPI class instance
    try:
        zapi = ZabbixAPI(url=zabbix_url, user=zabbix_user, password=zabbix_password)
    except Exception as e:
        print e, 'ZabbixAPI: Authenticate failed.'
        exit (-1)

    # Get Zabbix API version
    try:
        result_version = zapi.api_version()
    except:
        result_version = "2.4"

    # Hostgroup create
    hostgroup = system_name
    try:
        result_hostgroup = zapi.do_request('hostgroup.get', { 'filter': {'name': hostgroup}})
        if not result_hostgroup['result']:
    decode_user_attribute = json.loads(base64.b64decode(decode_consul_kv[0]["Value"]))
    zabbix_user = decode_user_attribute['zabbix_part']['zabbix_user']
    zabbix_password = decode_user_attribute['zabbix_part']['zabbix_password']
    zabbix_url = decode_user_attribute['zabbix_part']['zabbix_url']
    zabbix_template = decode_user_attribute['zabbix_part']['zabbix_template']

    # Getting Consul KV
    consul_kv = get_kv("cloudconductor/system_domain",ret_url_encode(os.environ['CONSUL_SECRET_KEY']))
    decode_consul_kv = json.loads(consul_kv)
    decode_user_attribute = json.loads(base64.b64decode(decode_consul_kv[0]["Value"]))
    system_domain = decode_user_attribute['dns']
    system_name = decode_user_attribute['name']

    # Create ZabbixAPI class instance
    try:
        zapi = ZabbixAPI(url=zabbix_url, user=zabbix_user, password=zabbix_password)
    except Exception, e:
        print e, 'ZabbixAPI: Authenticate failed.'

    # Get Zabbix API version
    try:
        result_version = zapi.api_version()
    except:
        result_version = "2.4"

    # Hostgroup get
    hostgroup = system_name
    try:
        result_hostgroup = zapi.do_request('hostgroup.get', { 'filter': {'name': hostgroup}})
        if not result_hostgroup['result']:
            print 'Can not be found host group ' + hostgroup
示例#37
0
    except KeyError, e:
        module.fail_json(msg='Missing actions data: %s is not set.' % e.message)

    try:
        login = module.params['login']
        password = module.params['password']
        server = module.params['server']
    except KeyError, e:
        module.fail_json(msg='Missing login data: %s is not set.' % e.message)

    try:
        zabbix_object = module.params['object']
        params = module.params['params']
    except KeyError, e:
        module.fail_json(msg='Missing actions data: %s is not set.' % e.message)

    try:
        zapi = ZabbixAPI(url=server, user=login, password=password)
    except BaseException as e:
        module.fail_json(msg='Authentication error: %s' % e)

    try:
        request = zapi.do_request(zabbix_object + '.' + action, params)
    except BaseException as e:
        module.fail_json(msg='Request error: %s ' % e)

    module.exit_json(changed=1, ansible_facts={'response': request})

main()

示例#38
0
文件: cli.py 项目: blacked/zabbixcli
class ZabbixCLI(ZabbixCLIArguments):

    def __init__(self, template=None):
        ZabbixCLIArguments.__init__(self)
        self._configureLogging()
        log.debug('Parser arguments: %s', self.args)

        # if no arguments, jsut print help
        if len(sys.argv) <= 1:
            self.argparser.print_help()
            sys.exit()

        if not self.args.get('template'):
            sys.exit('Template should be specified.')

        self.url = self.args['server']
        try:
            self.zapi = ZabbixAPI(
                self.url,
                user=self.args['user'],
                password=self.args['pass'])
        except:
            log.error('Error while trying open connection to zabbix server: %s',
                    self.url)

        # If we need to delete an object and exit
        if self.args.get('delete'):
            template_id = self.zapi.get_id('template', self.args['delete'][1])
            if ZabbixObject(self.zapi,
                            {'name': self.args['delete'][2]},
                            template_id=template_id,
                            obj_type=self.args['delete'][0]).delete():
                log.info(
                    '"{2}" {0} was deleted from "{1}"'.format(
                        *self.args['delete']))
            else:
                log.exit(
                    'Error while trying to delete: "{2}" {0} from "{1}"'.format(
                        *self.args['delete']))
            exit()

        # Set template name from __init__ params or args
        if template:
            self.template_name = template
        else:
            self.template_name = self.args.get('template')

        # Load template from file
        self.template = ZabbixTemplateFile(self.template_name, templates_dir=self.args.get('templates_dir'))
        self.template_id = None

        # When template loaded, set defaults and run apply process
        if self.template:
            self.config = ZabbixDefaults()
            self.apply()

    def _configureLogging(self):
        """
        Configure logging output. Format and colors.
        """

        # Set logging level
        if self.args.get('debug'):
            logLevel = logging.DEBUG
        else:
            logLevel = logging.INFO

        # Set colored output
        colors = {'reset': '\033[0m', 'green': '\x1b[32m', 'cyan': '\x1b[36m'}
        logFormat = '{reset}{cyan}[{green}%(asctime)s{cyan}]{reset} %(message)s'.format(
            **colors)
        logging.basicConfig(
            level=logLevel,
            format=logFormat,
            datefmt='%d/%m/%Y %H:%M:%S')

    def _apply_linked_templates(self):
        """
        Recursive apply list of linked templates. They will applied before main
        template will start applying.
        """

        if self.template.get('templates') and not self.args.get('only', False):
            log.info('%s depends from:', self.template.get('name'))
            # Show linked template list before applying
            for linked_template in self.template.get('templates', []):
                log.info("\t\t%s", linked_template)
            # Apply list of linked templates
            for linked_template in self.template.get('templates', []):
                ZabbixCLI(template=linked_template)

    def _apply_template(self, template):
        return ZabbixTemplate(self.zapi, template).apply()

    def _apply_macro(self, macro):
        ZabbixMacro(self.zapi, macro, self.template_id).apply()

    def _apply_macros(self):
        for macro in self.template.get('macros', []):
            self._apply_macro(macro)

    def _apply_app(self, app):
        return ZabbixApp(self.zapi, app, self.template_id).apply()

    def _apply_item(self, item):
        ZabbixItem(self.zapi, item, self.config, self.template_id).apply()

    def _apply_items(self, items, app_id):
        for item in items:
            item['app_id'] = app_id
            self._apply_item(item)

    def _apply_item_prototype(self, prototype):
        ZabbixItemPrototype(self.zapi, prototype, self.config, self.template_id).apply()

    def _apply_item_prototypes(self, discovery, app_id):
        items = discovery.get('items', [])
        rule_id = self.zapi.get_id(
            'discoveryrule',
            discovery['name'],
            templateid=self.template_id)
        for item in items:
            item.update({'rule_id': rule_id, 'app_id': app_id})
            self._apply_item_prototype(item)

    def _apply_graph(self, graph):
        ZabbixGraph(self.zapi, graph, self.config, self.template_id).apply()

    def _apply_graphs(self):
        for graph in self.template.get('graphs', []):
            self._apply_graph(graph)

    def _apply_graph_prototype(self, prototype):
        ZabbixGraphPrototype(self.zapi, prototype, self.config, self.template_id).apply()

    def _apply_graph_prototypes(self, discovery):
        graphs = discovery.get('graphs', [])
        for graph in graphs:
            self._apply_graph_prototype(graph)

    def _apply_trigger(self, trigger):
        ZabbixTrigger(self.zapi, trigger, self.config, self.template_id).apply()

    def _apply_triggers(self):
        for trigger in self.template.get('triggers', []):
            self._apply_trigger(trigger)

    def _apply_trigger_prototype(self, prototype):
        ZabbixTriggerPrototype(self.zapi, prototype, self.config, self.template_id).apply()

    def _apply_trigger_prototypes(self, discovery):
        triggers = discovery.get('triggers', [])
        for triggers in triggers:
            self._apply_trigger_prototype(triggers)

    def _apply_autoreg(self):
        autoreg = self.template.get('autoreg')
        if autoreg:
            ZabbixAutoreg(self.zapi, self.template).apply()

    def _apply_trigger_action(self):
        alerts = self.template.get('alerts', [])
        for alert in alerts:
            ZabbixTriggerAction(self.zapi, alert, self.config, self.template_id, self.template_name).apply()

    def _apply_discovery(self, discovery):
        ZabbixDiscovery(self.zapi, discovery, self.config, self.template_id).apply()

    def _apply_discoveries(self):
        discoveries = self.template.get('discovery', {})

        for app, discovery in discoveries.iteritems():
            app_id = self._apply_app(app)
            self._apply_discovery(discovery)
            self._apply_item_prototypes(discovery, app_id)
            self._apply_graph_prototypes(discovery)
            self._apply_trigger_prototypes(discovery)

    def _disable_item(self, id_):
        ZabbixItem(self.zapi).disable(id_)

    def _disable_app(self, app):
        items = self.zapi.get_id(
            'item',
            None,
            hostid=self.template_id,
            app_name=app)
        for item in items:
            self._disable_item(item)

    def clean(self):
        """
        Find and clean unused zabbix objects in current template.
        """

        def getUnusedObjects(type_, o):
            """
            Return list of unused zabbix objects of specific type in current template
            """

            unused_items = []
            # Get current objects from current template
            current_items = self.zapi.get_id(type_, templateids=self.template_id, name=True)
            if current_items:
                log.debug("Current %s: %s", type_, current_items)
                template_items = []
                for item in o:
                    if isinstance(item, dict):
                        template_items.append(item.get('name'))
                    else:
                        template_items.append(item)
                log.debug("Template %s: %s", type_, template_items)
                # Filter out similar objects from zabbix and template
                unused_items = filter(lambda x: x not in template_items, current_items)
                log.debug("Unused %s: %s", type_, unused_items)
            return { type_: unused_items }

        def removeObjects(template_objects):
            """
            Remove unused zabbix objects in current template.
            """

            # Find unused objects
            for objects in template_objects:
                unused_objects = getUnusedObjects(*objects)
                # Process each object type
                for type_, objects_list in unused_objects.iteritems():
                    # Get zabbix id for each unused object
                    for name in objects_list:
                        object_id = self.zapi.get_id(type_, name)
                        if object_id:
                            # Make function to remove object
                            func = 'self.zapi.{object_type}.delete'.format(object_type=type_)
                            log.info('Unused: %s \'%s\' was removed', type_, name)
                            eval(func)(object_id)

        # Init lists for objects
        items = apps = discovery = itemprototype = graphprototype = triggerprototype = []

        for app, item in self.template.get('applications', {}).iteritems():
            apps.append(app)
            items.extend(item)
        for app, disc in self.template.get('discovery', {}).iteritems():
            apps.append(app)
            discovery.append(disc)
            itemprototype.extend(disc.get('items', {}))
            graphprototype.extend(disc.get('graphs',{}))
            triggerprototype.extend(disc.get('triggers', {}))

        # Cleanup should be executed in folowing order
        obj_for_cleanup = collections.OrderedDict()
        obj_for_cleanup['application'] = apps
        obj_for_cleanup['item'] = items
        obj_for_cleanup['usermacro'] = map(lambda x: {'name':x.get('macro')}, self.template.get('macros', []))
        obj_for_cleanup['graph'] = self.template.get('graphs', [])
        obj_for_cleanup['trigger'] = self.template.get('triggers', [])
        obj_for_cleanup['discoveryrule'] = discovery
        obj_for_cleanup['itemprototype'] = itemprototype
        obj_for_cleanup['graphprototype'] = graphprototype
        obj_for_cleanup['triggerprototype'] = triggerprototype

        # Make tuple (obj_type, value) to compare with
        template_objects = []
        for k,v in obj_for_cleanup.iteritems():
            template_objects.append((k,v))

        # Remove unused objects
        removeObjects(template_objects)

    def apply(self):
        """
        Apply current template to zabbix.
        """

        self._apply_linked_templates()
        self.template_id = self._apply_template(self.template)

        # Cleanup unused objects
        self.clean()

        apps = self.template.get('applications', {})
        for app, items in apps.iteritems():
            # check if disabled whole app
            if str(items).lower() == 'disabled':
                self._disable_app(app)
            else:
                app_id = self._apply_app(app)
                self._apply_items(items, app_id)

        self._apply_macros()
        self._apply_graphs()
        self._apply_triggers()
        self._apply_discoveries()
        self._apply_autoreg()
        self._apply_trigger_action()
        log.info("Done: '%s'", self.template.get('name'))
示例#39
0
#!/usr/bin/env python

import sys
from zabbix.api import ZabbixAPI

if len(sys.argv) > 1:
    hostname = sys.argv[1]

z = ZabbixAPI(
        url='https://zabbix.local',
        user='******',
        password='******')

# Get zabbix host id
hostId = z.get_id('host', hostname)

# Remove host by id
result = z.do_request('host.delete', [hostId]).get('result', {}).get('hostids',[None])[0]

# Output
if result:
    print '{hostname} removed from zabbix.'.format(hostname=hostname)
else:
    sys.exit(1)