Exemplo n.º 1
2
def main():
    """The main function"""
    login = "******"#raw_input("Login: "******"1kassiope@"#raw_input("Password: "******"Connected to Zabbix API Version %s" % zapi.api_version()
    template_id = zapi.template.get({"output": "extend", "search": {"name": 'App RabbitMQ'}})[0]["templateid"]
    print "Template ID", template_id
    hosts = []
    items = {}
    gitems = {}
    print "Host IDs:"
    for rig in zapi.host.get({"templateids":template_id}):
        hosts.append(rig["hostid"])
        print rig["hostid"], rig["name"]
    print "Collecting items and assigning colors to them..."
    for i in hosts:
        items[i] = zapi.item.get({"hostids": i, "search": {"key_": 'queue_message_stats'}})
        gitems[i] = []
        for j in items[i]:
            gitems[i].append({"itemid": j["itemid"], "color": '%02X%02X%02X' % (rand(), rand(), rand())})
        print "Creating graph for", i
        try:
            zapi.graph.create({"name": "Aggregated queue stats", "width": 900, "height": 300, "gitems": gitems[i]})
        except:
            print "Graph already exists or cannot be created"
            continue
    print "All done"
Exemplo n.º 2
2
def main():
    global zapi, hostid

    zapi = ZabbixAPI(server=server, path="", log_level=6)
    zapi.login(username, password)

    hostid = zapi.host.get({"filter":{"host":hostname}})[0]["hostid"]
    #print hostid

    add_counters(hrl)
Exemplo n.º 3
1
class zabbix:
    def __init__(self,server=None,log_level=0,log=None):
        """
        Accepts keyword args for Server and log_level

        @type server: str
        @param server: Zabbix Server URL
        @type log_level: int
        @param log_level: Logging level for this class
        
        """
        self.zapi = ZabbixAPI(server=server,log_level=log_level)
        if log == None:
            self._log = setup_logging()
        else:
            self._log = log

    def login(self,username=None,password=None):
        """
        Login handler

        """
        try:
            self._log.debug("Attempting to login")
            self.zapi.login(username,password)
            self._log.debug("Login successfull")
        except Exception, e:
            # Unable to login, lets just bomb out
            self._log.error("Failed to login - exiting")
            sys.exit()
Exemplo n.º 4
1
    def get_metric(self, host, item, **kwargs):
        """
        Returns the last value of "item" from "host"

        :param host: hostname of itemholder
        :param item: itemname of wanted item
        :param kwargs: Optional parameter
        :return:
        """
        if self.__address is not None:
            if 'password' in kwargs:
                password = kwargs['password']
            else:
                password = '******'
            if 'username' in kwargs:
                username = kwargs['username']
            else:
                username = '******'

            zapi = ZabbixAPI(server='http://'+self.__address+'/zabbix',
                             path="", log_level=0)
            zapi.login(username, password)
            hostid = zapi.host.get({"filter": {"host": host}})[0]["hostid"]

            item_values = zapi.item.get({"params": {"hostids": hostid},
                                         "filter": {"name": item,
                                                    "hostid": hostid}})

            return item_values[0]["lastvalue"]
        else:
            return None
Exemplo n.º 5
0
def createhost():
    zapi = ZabbixAPI(server="http://192.168.1.0")
    zapi.login("Admin", "zabbix")
    zabbixhost = raw_input("Defina o nome do host: ")
    zabbixhostip = raw_input("Digite o ip do host %s: " % zabbixhost)
    group = zapi.hostgroup.get({})
    template = zapi.template.get({})
    for i, x in enumerate(group):
        print "Indice:", i, "-", "ID:", x["groupid"], "-", x["name"]
    indicegroup = input("Escolha o indice do grupo desejado para o host %s: " %
                        zabbixhost)
    askgroup = raw_input("O grupo %s foi selecionado. Confirma? (s ou n): " %
                         group[indicegroup]["name"])
    if askgroup == 'n':
        print "grupo nao confirmado"
    elif askgroup == 's':
        for i, y in enumerate(template):
            print "Indice:", i, "-", "Template ID :", y["templateid"], "-", y[
                "host"]
        indicetemplate = input(
            "Escolha o indice do template desejado para o host %s: " %
            zabbixhost)
        asktemplate = raw_input(
            "O template %s foi selecionado. Confirma? (s ou n): " %
            template[indicetemplate]["host"])
        if asktemplate == 'n':
            print "Template nao confirmado"
        elif asktemplate == 's':
            print "Host: %s" % zabbixhost
            print "IP: %s" % zabbixhostip
            print "Grupo: %s" % group[indicegroup]["name"]
            print "Template: %s" % template[indicetemplate]["host"]
            confirmhost = raw_input(
                "Confirma as informacoes e criar host %s? (s ou n): " %
                zabbixhost)
            if confirmhost == 'n':
                print "O host %s nao foi criado" % zabbixhost
            if confirmhost == 's':
                zapi.host.create({
                    "host":
                    zabbixhost,
                    "status":
                    0,
                    "interfaces": [{
                        "type": 1,
                        "main": 1,
                        "useip": 1,
                        "ip": zabbixhostip,
                        "dns": "",
                        "port": 10050
                    }],
                    "groups": [{
                        "groupid": group[indicegroup]["groupid"]
                    }],
                    "templates": [{
                        "templateid":
                        template[indicetemplate]["templateid"]
                    }]
                })
            print "O host %s foi criado" % zabbixhost
Exemplo n.º 6
0
    def __init__(self):

        self.defaultgroup = 'group_all'
        self.zabbix_server = None
        self.zabbix_username = None
        self.zabbix_password = None

        self.read_settings()
        self.read_cli()

        if self.zabbix_server and self.zabbix_username:
            try:
                api = ZabbixAPI(server=self.zabbix_server)
                api.login(user=self.zabbix_username,
                          password=self.zabbix_password)
            except BaseException, e:
                print >> sys.stderr, "Error: Could not login to Zabbix server. Check your zabbix.ini."
                sys.exit(1)

            if self.options.host:
                data = self.get_host(api, self.options.host)
                print json.dumps(data, indent=2)

            elif self.options.list:
                data = self.get_list(api)
                print json.dumps(data, indent=2)

            else:
                print >> sys.stderr, "usage: --list  ..OR.. --host <hostname>"
                sys.exit(1)
Exemplo n.º 7
0
    def Zabbix(self, request):
        """
        self.config['zabbix']['api']['username']
        self.config['zabbix']['api']['password']
        self.config['zabbix']['api']['server']
        self.config['zabbix']['api']['verify_tls']
        """
        try:
            zapi = ZabbixAPI(
                server=self.config['zabbix']['api']['server'],
                validate_certs=self.config['zabbix']['api']['verify_tls'])
            zapi.login(self.config['zabbix']['api']['username'],
                       self.config['zabbix']['api']['password'])
            hosts = zapi.host.get({
                'monitored_hosts': True,
                'extendoutput': True
            })
        except Exception:
            request.setResponseCode(500)
            request.write(f'API ERROR'.encode())
            request.finish()
            return

        if len(hosts) < 1:
            request.setResponseCode(201)
            request.write('NOT OK - No hosts found {len(hosts)}'.encode())
            request.finish()
            return

        request.write('OK'.encode())
        request.finish()
Exemplo n.º 8
0
    def __init__(self):

        self.defaultgroup = 'group_all'
        self.zabbix_server = None
        self.zabbix_username = None
        self.zabbix_password = None
        self.validate_certs = True
        self.meta = {}

        self.read_settings()
        self.read_cli()

        if self.zabbix_server and self.zabbix_username:
            try:
                api = ZabbixAPI(server=self.zabbix_server, validate_certs=self.validate_certs)
                api.login(user=self.zabbix_username, password=self.zabbix_password)
            except BaseException as e:
                print("Error: Could not login to Zabbix server. Check your zabbix.ini.", file=sys.stderr)
                sys.exit(1)

            if self.options.host:
                data = self.get_host(api, self.options.host)
                print(json.dumps(data, indent=2))

            elif self.options.list:
                data = self.get_list(api)
                print(json.dumps(data, indent=2))

            else:
                print("usage: --list  ..OR.. --host <hostname>", file=sys.stderr)
                sys.exit(1)

        else:
            print("Error: Configuration of server and credentials are required. See zabbix.ini.", file=sys.stderr)
            sys.exit(1)
Exemplo n.º 9
0
    def __init__(self):

        self.defaultgroup = 'group_all'
        self.zabbix_server = None
        self.zabbix_username = None
        self.zabbix_password = None

        self.read_settings()
        self.read_cli()

        if self.zabbix_server and self.zabbix_username:
            try:
                api = ZabbixAPI(server=self.zabbix_server)
                api.login(user=self.zabbix_username, password=self.zabbix_password)
            except BaseException, e:
                print "Error: Could not login to Zabbix server. Check your zabbix.ini."
                sys.exit(1)

            if self.options.host:
                data = self.get_host(api, self.options.host)
                print json.dumps(data, indent=2)

            elif self.options.list:
                data = self.get_list(api)
                print json.dumps(data, indent=2)

            else:
                print "usage: --list  ..OR.. --host <hostname>"
                sys.exit(1)
Exemplo n.º 10
0
def update_host(hostname, status):
    """Enable or disable monitoring for the host"""

    # Suppress SSL Verification check
    ssl._create_default_https_context = ssl._create_unverified_context

    server = "https://" + get_zabbix_server(hostname)
    zapi = ZabbixAPI(server)

    # Disable SSL certificate verification
    zapi.session.verify = False

    username = os.getenv("RD_CONFIG_USERNAME")
    password = os.getenv("RD_CONFIG_PASSWORD")

    # Specify a timeout (in seconds)
    zapi.timeout = 5
    zapi.login(username, password)

    try:
        hostid = zapi.host.get({
            "output": ["hostid"],
            "filter": {
                "host": [hostname]
            }
        })[0]['hostid']
    except Exception as e:
        exit(1)
    try:
        zapi.host.update({"hostid": hostid, "status": status})
    except Exception as e:
        print(e)
        exit(1)
Exemplo n.º 11
0
class AnsibleZabbix(object):

    def __init__(self, module):
        if not HAS_ZABBIX_API:
            module.fail_json(msg="python library zabbix-api required: pip install zabbix-api")

        self._module = module
        self._connect()

    def _connect(self):
        server_url = self._module.params['server_url']
        login_user = self._module.params['login_user']
        login_password = self._module.params['login_password']
        http_login_user = self._module.params['http_login_user']
        http_login_password = self._module.params['http_login_password']
        timeout = self._module.params['timeout']

        try:
            self._zapi = ZabbixAPI(
                server_url,
                timeout=timeout,
                user=http_login_user,
                passwd=http_login_password
            )
            self._zapi.login(login_user, login_password)
        except Exception as e:
            self._module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True, default=None, aliases=['url']),
            login_user=dict(required=True),
            login_password=dict(required=True),
            host_groups=dict(required=True),
            state=dict(default="present"),
            timeout=dict(default=10)
        ),
        supports_check_mode=True
    )

    if not HAS_ZABBIX_API:
        module.fail_json(msg="Missing requried zabbix-api module (check docs or install with: pip install zabbix-api)")

    server_url = module.params['server_url']
    login_user = module.params['login_user']
    login_password = module.params['login_password']
    host_groups = module.params['host_groups']
    state = module.params['state']
    timeout = module.params['timeout']

    zbx = None

    # login to zabbix
    try:
        zbx = ZabbixAPI(server_url, timeout=timeout)
        zbx.login(login_user, login_password)
    except Exception, e:
        module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)
Exemplo n.º 13
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(type='str', required=True, aliases=['url']),
            login_user=dict(type='str', required=True),
            login_password=dict(type='str', required=True, no_log=True),
            http_login_user=dict(type='str',required=False, default=None),
            http_login_password=dict(type='str',required=False, default=None, no_log=True),
            host_groups=dict(type='list', required=True, aliases=['host_group']),
            state=dict(default="present", choices=['present','absent']),
            timeout=dict(type='int', default=10)
        ),
        supports_check_mode=True
    )

    if not HAS_ZABBIX_API:
        module.fail_json(msg="Missing requried zabbix-api module (check docs or install with: pip install zabbix-api)")

    server_url = module.params['server_url']
    login_user = module.params['login_user']
    login_password = module.params['login_password']
    http_login_user = module.params['http_login_user']
    http_login_password = module.params['http_login_password']
    host_groups = module.params['host_groups']
    state = module.params['state']
    timeout = module.params['timeout']

    zbx = None

    # login to zabbix
    try:
        zbx = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password)
        zbx.login(login_user, login_password)
    except Exception, e:
        module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)
Exemplo n.º 14
0
    def __init__(self):

        self.defaultgroup = 'group_all'
        self.zabbix_server = None
        self.zabbix_username = None
        self.zabbix_password = None

        self.read_settings()
        self.read_cli()

        if self.zabbix_server and self.zabbix_username:
            try:
                api = ZabbixAPI(server=self.zabbix_server)
                api.login(user=self.zabbix_username, password=self.zabbix_password)
            except BaseException as e:
                print("Error: Could not login to Zabbix server. Check your zabbix.ini.", file=sys.stderr)
                sys.exit(1)

            if self.options.host:
                data = self.get_host(api, self.options.host)
                print(json.dumps(data, indent=2))

            elif self.options.list:
                data = self.get_list(api)
                print(json.dumps(data, indent=2))

            else:
                print("usage: --list  ..OR.. --host <hostname>", file=sys.stderr)
                sys.exit(1)

        else:
            print("Error: Configuration of server and credentials are required. See zabbix.ini.", file=sys.stderr)
            sys.exit(1)
Exemplo n.º 15
0
 def test_login(self, host):
     try:
         zapi = ZabbixAPI(server="http://{0}/zabbix".format(host))
         zapi.login("Admin", "zabbix")
         print("[success] - {0} - User: Admin - Pass: zabbix".format(host))
     except:
         pass
Exemplo n.º 16
0
def LoginZabbixServer(server, username, password):

    try:
        zapi = ZabbixAPI(server=server, path="", log_level=6)
        zapi.login(username, password)
    except ZabbixAPIException, e:
        print e
        return False, None
Exemplo n.º 17
0
def printHostList():
    zapi = ZabbixAPI(server=server)
    zapi.login(settings['zabbixusername'], settings['zabbixpassword'])

    result = zapi.host.get({"output": "extend"})
    hostlist = []
    for i in result:
        print i["name"]
Exemplo n.º 18
0
def printHostList() :
   zapi = ZabbixAPI(server=server)
   zapi.login(settings['zabbixusername'], settings['zabbixpassword'])

   result = zapi.host.get({"output": "extend"})
   hostlist = []
   for i in result :
      print i["name"]
Exemplo n.º 19
0
def zabbix_auth(server, username, password):
    try:
        zapi = ZabbixAPI(server)
        zapi.login(username, password)
        return zapi
    except:
        print "Unexpected error:", sys.exc_info()[0]
        raise
Exemplo n.º 20
0
def api_connect():
    """Connect to Zabbix API"""
    try:
    	zapi = ZabbixAPI(server=ZABBIX['url'])
    	zapi.login(ZABBIX['user'], ZABBIX['pass'])
    except Exception,e:
    	logger.error("Can't login to zabbix server: %s" %(e))
	raise ZabbixAlarms, "Can't login to zabbix server: %s" %(e)
Exemplo n.º 21
0
def api_connect():
    """Connect to Zabbix API"""
    try:
        zapi = ZabbixAPI(server=ZABBIX['url'])
        zapi.login(ZABBIX['user'], ZABBIX['pass'])
    except Exception, e:
        logger.error("Can't login to zabbix server: %s" % (e))
        raise ZabbixAlarms, "Can't login to zabbix server: %s" % (e)
Exemplo n.º 22
0
def connect_api():
    try:
        zapi = ZabbixAPI(URL)
        zapi.login(user=USERNAME, password=PASSWORD)
        print(f'Conectado na API do Zabbix')
        return zapi
    except Exception as err:
        print(f'Falha ao conectar na API: {err}')
Exemplo n.º 23
0
def login():
    zapi = ZabbixAPI(server=server, path=path, log_level=0)

    try:
        zapi.login(username, password)
    except Exception:
        print 'Login Faild!'
        sys.exit()
    return zapi
def main():
    module = AnsibleModule(argument_spec=dict(
        server_url=dict(type='str', required=True, aliases=['url']),
        login_user=dict(type='str', required=True),
        login_password=dict(type='str', required=True, no_log=True),
        http_login_user=dict(type='str', required=False, default=None),
        http_login_password=dict(type='str',
                                 required=False,
                                 default=None,
                                 no_log=True),
        validate_certs=dict(type='bool', required=False, default=True),
        timeout=dict(type='int', default=10),
        template_name=dict(type='str', required=True),
        format=dict(type='str', choices=['json', 'xml'], default='json')),
                           supports_check_mode=False)

    if not HAS_ZABBIX_API:
        module.fail_json(msg=missing_required_lib(
            'zabbix-api', url='https://pypi.org/project/zabbix-api/'),
                         exception=ZBX_IMP_ERR)

    server_url = module.params['server_url']
    login_user = module.params['login_user']
    login_password = module.params['login_password']
    http_login_user = module.params['http_login_user']
    http_login_password = module.params['http_login_password']
    validate_certs = module.params['validate_certs']
    timeout = module.params['timeout']
    template_name = module.params['template_name']
    format = module.params['format']

    try:
        zbx = ZabbixAPI(server_url,
                        timeout=timeout,
                        user=http_login_user,
                        passwd=http_login_password,
                        validate_certs=validate_certs)
        zbx.login(login_user, login_password)
        atexit.register(zbx.logout)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)

    template_info = TemplateInfo(module, zbx)

    template_id = template_info.get_template_id(template_name)

    if not template_id:
        module.fail_json(msg='Template not found: %s' % template_name)

    if format == 'json':
        module.exit_json(changed=False,
                         template_json=template_info.dump_template(
                             template_id, template_type='json'))
    elif format == 'xml':
        module.exit_json(changed=False,
                         template_xml=template_info.dump_template(
                             template_id, template_type='xml'))
Exemplo n.º 25
0
 def GET(self):
     web.header('Content-Type', 'application/xml')
     zabbix = ZabbixAPI(server=args.url)
     zabbix.login(args.user, args.password)
     events = zabbix.event.get(
             {"limit": 100, "sortfield": "clock", "sortorder": "DESC", "extendoutput": True, "selectHosts": "extend",
              "selectRelatedObject": "extend"})
     records = [x for x in [makeRecord(zabbix, e) for e in events] if x is not None]
     return render.rss(records=records, date=datetime.now() if len(records) == 0 else records[-1].date)
Exemplo n.º 26
0
def get_host_id(host_name):
    zapi = ZabbixAPI(server='http://127.0.0.1/zabbix')
    zapi.login('svc_monitoria', 'vk98v#m$')
    host_response = zapi.host.get(
        {'filter': {
            'host': str(host_name.rstrip())
        }})  #[0]['hostid']
    host_id = host_response[0]['hostid']

    return host_id
Exemplo n.º 27
0
def main():
    # noinspection PyShadowingBuiltins
    module = AnsibleModule(argument_spec=dict(
        server_url=dict(required=True, default=None, aliases=['url']),
        login_user=dict(required=True),
        login_password=dict(required=True),
        api_method=dict(required=True),
        api_params_dict=dict(required=False, type='dict', default={}),
        api_params_list=dict(required=False, type='list', default=[]),
        timeout=dict(default=10, type='int'),
        validate_certs=dict(required=False, default=False, type='bool')),
                           supports_check_mode=True)

    if not ZabbixAPI:
        module.fail_json(
            msg=
            "Missing required zabbix-api module (check docs or install with: "
            "pip install zabbix-api-erigones)")
        raise AssertionError

    server_url = module.params['server_url']
    login_user = module.params['login_user']
    login_password = module.params['login_password']
    api_method = module.params['api_method']
    api_params = module.params['api_params_list'] or module.params[
        'api_params_dict']
    timeout = module.params['timeout']
    ssl_verify = module.params['validate_certs']

    # login to zabbix
    try:
        # noinspection PyCallingNonCallable
        zbx = ZabbixAPI(server=server_url,
                        timeout=timeout,
                        ssl_verify=ssl_verify)
        zbx.login(login_user, login_password)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)
        raise AssertionError

    try:
        result = zbx.call(api_method, api_params)
    except ZabbixAPIException as e:
        module.fail_json(msg="Zabbix API error: %s" % e)
        raise AssertionError
    except Exception as e:
        module.fail_json(msg="Unknown failure: %s" % e)
        raise AssertionError
    else:
        if api_method.endswith(('.get', '.isreadable', '.iswritable')):
            changed = False
        else:
            changed = True

    module.exit_json(changed=changed, result=result)
Exemplo n.º 28
0
def main():
    module = AnsibleModule(argument_spec=dict(
        server_url=dict(type='str', required=True, aliases=['url']),
        login_user=dict(type='str', required=True),
        login_password=dict(type='str', required=True, no_log=True),
        http_login_user=dict(type='str', required=False, default=None),
        http_login_password=dict(type='str',
                                 required=False,
                                 default=None,
                                 no_log=True),
        validate_certs=dict(type='bool', required=False, default=True),
        alias=dict(type='str', required=True),
        passwd=dict(type='str', required=True, no_log=True),
        timeout=dict(type='int', default=10)),
                           supports_check_mode=True)

    if not HAS_ZABBIX_API:
        module.fail_json(msg=missing_required_lib(
            'zabbix-api', url='https://pypi.org/project/zabbix-api/'),
                         exception=ZBX_IMP_ERR)

    server_url = module.params['server_url']
    login_user = module.params['login_user']
    login_password = module.params['login_password']
    http_login_user = module.params['http_login_user']
    http_login_password = module.params['http_login_password']
    validate_certs = module.params['validate_certs']
    alias = module.params['alias']
    passwd = module.params['passwd']
    timeout = module.params['timeout']

    zbx = None

    # login to zabbix
    try:
        zbx = ZabbixAPI(server_url,
                        timeout=timeout,
                        user=http_login_user,
                        passwd=http_login_password,
                        validate_certs=validate_certs)
        zbx.login(login_user, login_password)
        atexit.register(zbx.logout)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)

    user = User(module, zbx)

    user_ids = {}
    zbx_api_version = zbx.api_version()[:3]
    zbx_user = user.check_user_exist(alias)

    if zbx_user:
        user_ids = user.passwd(zbx_user, alias, passwd, zbx_api_version)

    module.exit_json(changed=True, user_ids=user_ids)
Exemplo n.º 29
0
    def test_login(self, host):
        try:
            zapi = ZabbixAPI(server="http://{0}/zabbix".format(host),
                             timeout=5)

            zapi.login("Admin", "zabbix")
            msg = "[success] -\t {0} \t- User: Admin - Password: zabbix".format(
                host)
            self.print_success(msg)
        except:
            pass
Exemplo n.º 30
0
class ICNaaSMonitor(object):

    def __init__(self, maas_endpoint):
        """
        Initialize the ICNaaS Monitor object
        """
        # Connect to MaaS
        if maas_endpoint is None:
            self.maas_endpoint = '130.92.70.142'
        else:
            self.maas_endpoint = maas_endpoint
        self.server = 'http://' + self.maas_endpoint + '/zabbix'
        self.username = MAAS_UID
        self.password = MAAS_PWD
        self.connFailed = False

        # Zabbix API
        self.zapi = ZabbixAPI(server=self.server)
        for i in range(1,4):
            try:
                print('*** Connecting to MaaS at ' + self.server)
                self.zapi.login(self.username, self.password)
                print('*** Connected to MaaS')
                self.connFailed = False
                break
            except Exception as e:
                print('*** Caught exception: %s: %s' % (e.__class__, e))
                traceback.print_exc()
                print('*** Connection to MaaS has failed! Retrying ('+str(i)+').')
                self.connFailed = True
            time.sleep(3)
        if self.connFailed:
            print('*** Connection to MaaS has failed! Waiting for an update to try again.')
        self.__metrics = []

    @property
    def metrics(self):
        return self.__metrics

    @metrics.setter
    def metrics(self, value):
        self.__metrics = value
        pass

    def get(self, public_ip):
        measured_values = {}
        for metric in self.metrics:
            measured_values[metric] = self.get_value(metric, public_ip)
            if measured_values[metric] is None:
                return
        return measured_values

    def get_value(self, metric, public_ip):
        raise NotImplementedError
Exemplo n.º 31
0
def delHostZabbix(ip):

	# login to zabbix server
	zapi = ZabbixAPI(server=ZAB_CONF['server'], path="", log_level=6)
	zapi.login(ZAB_CONF['username'], ZAB_CONF['password'])
	
	hostids=zapi.host.get({"output":"extend", 'filter':{'ip':ip}})
	if len(hostids) == 1:
		return hostids[0]['hostid']
	else:
		print bold +"\nNothing founded. Please make sure you specified a correct IP \n"+reset
	result=zapi.host.delete({"hostid":hostids})
Exemplo n.º 32
0
def create_hgroup() :
	global str_res

	try:
		zapi = ZabbixAPI(settings["zabbixurl"])
		zapi.login(settings["zabbixusername"],settings["zabbixpassword"])

		var = list_instances.list_instances() # list of dictionaries (name, id, vm)

	except Exception, error:
		print "Error connecting to Zabbix"
		raise error
def zabbix_set_status(hostname, status):

    #Set up variables
    zabbix_server = ""
    zabbix_user = ""
    zabbix_password = ""

    #Check if os variables are provided
    try:
        zabbix_server = os.environ['ZABBIX_SERVER']
        zabbix_user = os.environ['ZABBIX_USER']
        zabbix_password = os.environ['ZABBIX_PASSWORD']
    except:
        print("Zabbix enviroment varibles are not set ")
        print("ZABBIX_SERVER")
        print("ZABBIX_USER")
        print("ZABBIX_PASSWORD")

    #Connect to Zabbix API
    try:
        zabbix = ZabbixAPI(server=zabbix_server)
        zabbix.login(user=zabbix_user, password=zabbix_password)
    except:
        print(
            "Error connecting to Zabbix server. Please verify serve name, user and password"
        )

    try:
        host = zabbix.host.get({"filter": {"name": hostname}})

        print("Host Id:" + host[0]['hostid'])
        print("Host Name:" + host[0]['host'])
        print("Status:" + host[0]['status'])
    except:
        print("Error getting a host information  from Zabbix")

    host_id = host[0]["hostid"]

    try:
        print("Updating host status...")
        zabbix.host.update({"hostid": host_id, "status": status})
    except:
        print("Error chaning a status of host in Zabbix")

    try:
        host = zabbix.host.get({"filter": {"name": hostname}})

        print("Host Id:" + host[0]['hostid'])
        print("Host Name:" + host[0]['host'])
        print("Status:" + host[0]['status'])
    except:
        print("Error getting a host information  from Zabbix")
Exemplo n.º 34
0
def zabbixHostCreate(params):
    """
    To create the host in the zabbix server
    Args:
        {
            params - parameter dictionary
        }
    """
    #Setting the zabbix details
    zapi = ZabbixAPI(server = settings.ZABBIX_SERVER)
    zapi.login(settings.ZABBIX_USERNAME, settings.ZABBIX_PASSWORD)
    returnHost = zapi.host.create(params)
    return returnHost
Exemplo n.º 35
0
def create_hgroup():
    global str_res

    try:
        zapi = ZabbixAPI(settings["zabbixurl"])
        zapi.login(settings["zabbixusername"], settings["zabbixpassword"])

        var = list_instances.list_instances(
        )  # list of dictionaries (name, id, vm)

    except Exception, error:
        print "Error connecting to Zabbix"
        raise error
Exemplo n.º 36
0
def zabbixHostDelete(hostIdList):
    """
    To delete the host in the zabbix server
    hostIdList - The zabbix host id
    """
    
    try:
        zapi = ZabbixAPI(server = settings.ZABBIX_SERVER)
        zapi.login(settings.ZABBIX_USERNAME, settings.ZABBIX_PASSWORD)
        result = zapi.host.delete(hostIdList)
        return True
    except Exception, e:
        debugException(e)
def main():
    module = AnsibleModule(argument_spec=dict(
        server_url=dict(type='str', required=True, aliases=['url']),
        login_user=dict(type='str', required=True),
        login_password=dict(type='str', required=True, no_log=True),
        hostgroup_name=dict(type='list', required=True),
        http_login_user=dict(type='str', required=False, default=None),
        http_login_password=dict(type='str',
                                 required=False,
                                 default=None,
                                 no_log=True),
        validate_certs=dict(type='bool', required=False, default=True),
        timeout=dict(type='int', default=10)),
                           supports_check_mode=True)
    if module._name == 'zabbix_group_facts':
        module.deprecate(
            "The 'zabbix_group_facts' module has been renamed to 'zabbix_group_info'",
            collection_name="community.zabbix",
            version='2.0.0')  # was 2.13

    if not HAS_ZABBIX_API:
        module.fail_json(msg=missing_required_lib(
            'zabbix-api', url='https://pypi.org/project/zabbix-api/'),
                         exception=ZBX_IMP_ERR)

    server_url = module.params['server_url']
    login_user = module.params['login_user']
    login_password = module.params['login_password']
    http_login_user = module.params['http_login_user']
    http_login_password = module.params['http_login_password']
    validate_certs = module.params['validate_certs']
    hostgroup_name = module.params['hostgroup_name']
    timeout = module.params['timeout']

    zbx = None
    # login to zabbix
    try:
        zbx = ZabbixAPI(server_url,
                        timeout=timeout,
                        user=http_login_user,
                        passwd=http_login_password,
                        validate_certs=validate_certs)
        zbx.login(login_user, login_password)
        atexit.register(zbx.logout)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)

    host = Host(module, zbx)
    host_groups = host.get_group_ids_by_group_names(hostgroup_name)
    module.exit_json(host_groups=host_groups)
Exemplo n.º 38
0
def main():
    module = AnsibleModule(argument_spec=dict(
        server_url=dict(type='str', required=True, aliases=['url']),
        login_user=dict(type='str', required=True),
        login_password=dict(type='str', required=True, no_log=True),
        http_login_user=dict(type='str', required=False, default=None),
        http_login_password=dict(type='str',
                                 required=False,
                                 default=None,
                                 no_log=True),
        validate_certs=dict(type='bool', required=False, default=True),
        timeout=dict(type='int', default=10)),
                           supports_check_mode=False)

    if not HAS_ZABBIX_API:
        module.fail_json(
            msg=
            "Missing required zabbix-api module (check docs or install with: pip install zabbix-api)"
        )

    server_url = module.params['server_url']
    login_user = module.params['login_user']
    login_password = module.params['login_password']
    http_login_user = module.params['http_login_user']
    http_login_password = module.params['http_login_password']
    timeout = module.params['timeout']
    validate_certs = module.params['validate_certs']

    zbx = None

    # login to zabbix
    try:
        zbx = ZabbixAPI(server_url,
                        timeout=timeout,
                        user=http_login_user,
                        passwd=http_login_password,
                        validate_certs=validate_certs)
        zbx.login(login_user, login_password)
        module.exit_json(changed=False,
                         msg="Successfully logged in '{u}' at {s}!".format(
                             u=login_user, s=server_url))
    except Exception as e:
        module.fail_json(
            msg="Failed to connect to Zabbix server: {server} with {exception}"
            .format(server=server_url, exception=e))

    # rather a WIP/debug-fallthrough:
    module.exit_json(changed=True,
                     result="This module should not exit this way!")
Exemplo n.º 39
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(type='str', required=True, aliases=['url']),
            login_user=dict(type='str', required=True),
            login_password=dict(type='str', required=True, no_log=True),
            http_login_user=dict(type='str', required=False, default=None),
            http_login_password=dict(type='str', required=False, default=None, no_log=True),
            validate_certs=dict(type='bool', required=False, default=True),
            api_object=dict(type='str', required=True),
            api_method=dict(type='str', required=True),
            api_options=dict(type='dict', required=True),
            timeout=dict(type='int', default=10)
        ),
        supports_check_mode=False
    )

    if not HAS_ZABBIX_API:
        module.fail_json(msg="Missing required zabbix-api module (check docs or install with: pip install zabbix-api)")

    server_url = module.params['server_url']
    login_user = module.params['login_user']
    login_password = module.params['login_password']
    http_login_user = module.params['http_login_user']
    http_login_password = module.params['http_login_password']
    validate_certs = module.params['validate_certs']
    api_object = module.params['api_object']
    api_method = module.params['api_method']
    api_options = module.params['api_options']
    timeout = module.params['timeout']

    zbx = None

    # login to zabbix
    try:
        zbx = ZabbixAPI(server=server_url, timeout=timeout, user=http_login_user, passwd=http_login_password,
                        validate_certs=validate_certs)
        zbx.login(login_user, login_password)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Zabbix server: {server} with {exception}".format(server=server_url, exception=e))

    # select API Query based on parameters and execute it
    zbx_obj = getattr(zbx, api_object)
    zbx_method = getattr(zbx_obj, api_method)
    try:
        query_result = zbx_method(api_options)
        module.exit_json(changed=True, result=query_result)
    except Exception as e:
        module.fail_json(msg="Failed to execute api.{obj}.{meth}(): {exc}".format(obj=api_object, meth=api_method, exc=e))
class DataRetriever():
    server = "http://127.0.1.1/zabbix"
    username = "******"
    password = "******" 

    hist_type = 3
    dens = 1
    
    time_format = "%d-%m-%Y %H:%M:%S"
    
    def __init__(self, item_key):
        self.zapi = ZabbixAPI(server=self.server, path="", log_level=3)
        self.zapi.login(self.username, self.password)
        
        self.item_key = item_key
   
    def set_config(self, config):
        self.hist_type = config.get("general", "hist_type")
        self.dens = int(config.get("general", "dens"))

    # Time format: "%d-%m-%Y %H:%M:%s"
    def get_data(self, str_time_from, str_time_to):
        
        time_from = int(time.mktime(time.strptime(str_time_from, self.time_format)))
        time_to = int(time.mktime(time.strptime(str_time_to, self.time_format)))
        
        print str_time_from, time_from
        print str_time_to, time_to
        
        hostid = self.zapi.host.get({"output":"extend", "filter": {"host":"localhost"}})[0]["hostid"]
        itemid = self.zapi.item.get({"output" : "extend",
                                     "hostids" : [hostid], 
                                     "filter" : {"key_" : self.item_key}})[0]['itemid']

        H = self.zapi.history.get({"time_from" : str(time_from), 
                                   "time_till" : str(time_to), 
                                   "output":"extend", 
                                   "itemids" : [itemid],
                                   "hostids" : [hostid],
                                   "history" : self.hist_type})
        result = [[], []]
        i = 0
        for el in H:
            i += 1
            if i % self.dens == 0:
                result[0].append(int(el["clock"]) - time_from)
                result[1].append(float(el["value"]))
        
        return result
Exemplo n.º 41
0
    def run(self):
        properties = self.load_properties(self.parameter)

        zabbixServerHost = properties.get("zabbix_server")
        zapi = ZabbixAPI(server="http://" + zabbixServerHost)
        user = properties.get('username')
        passwd = properties.get('password')
        zapi.login(user, passwd)

        self.runPlugin()
        hostid = self.exist(zapi, host)
        if hostid > 0:
            self.parseReport(host, hostid, self.busReportDir, zapi)

        exit(0)
def zabbix_delete():
    z = ZabbixAPI(server = zabbix_srv)
    z.login(zabbix_usr, zabbix_pwd)
    for trigger in z.trigger.get({"output": [ "triggerid", "description", "priority" ], "filter": { "value": 1 }, "sortfield": "priority", "sortorder": "DESC"}):
        if trigger["description"] == 'Zabbix agent on {HOST.NAME} is unreachable for 5 minutes':
            trigmsg = z.trigger.get({"triggerids": trigger["triggerid"], "selectHosts": "extend"})
            for tm in trigmsg:
                for l in tm['hosts']:
                    host_ip = find_ip(l['host'])
                    if aws_check_status(host_ip) != True:
                        print l['name'], l['hostid']
                        print "Will kill host " + l['hostid'] + " " + l['host'] + trigger["description"]
                        z.host.delete( [int(l['hostid'])] )
                    else:
                        print "instance is running"
Exemplo n.º 43
0
def main():
    zapi = ZabbixAPI(server='http://zabbix-server01.dc.nova/zabbix')
    zapi.login(zabbix_user, zabbix_pwd)

    host_response = zapi.host.get({'groupids': [8,9],
                                   'selectInterfaces': 'extend'})

    hosts = []
    for host in host_response:
        hosts.append({'nome': host['host'],
                      'ip': host['interfaces'][0]['ip'],
                      'host_id': int(host['hostid'])})


    arquivo = os.path.dirname(os.path.realpath(__file__)) + '/servidores_zabbix.json'
    with open(arquivo, 'w') as arq:
        json.dump(hosts, arq)
Exemplo n.º 44
0
class ImportCommand(Command):
    description = "import zabbix global scripts and global macros"
    user_options = [("frontend-url=", "f", "zabbix frontend url"),
                    ("user="******"u", "zabbix user name"),
                    ("password="******"p", "zabbix password")]

    def initialize_options(self):
        # set default value
        self.frontend_url = "http://localhost/zabbix"
        self.user = "******"
        self.password = "******"

    def finalize_options(self):
        pass

    def run(self):
        from zabbix_api import ZabbixAPI, ZabbixAPIException
        from xml.etree import ElementTree
        # connect zabbix frontend
        try:
            self.zabbix_api = ZabbixAPI(self.frontend_url)
            self.zabbix_api.login(self.user, self.password)
        except ZabbixAPIException, e:
            print "Failed to connect zabbix frontend: %s" % str(e[0]).partition("while sending")[0]
            return
        # import templates
        print "Import templates"
        try:
            with open(os.path.join(pwd, "misc/import_data/templates.xml")) as f:
                template_xml = f.read()
                req = self.zabbix_api.json_obj("configuration.import", {
                    "format": "xml",
                    "source": template_xml,
                    "rules": {
                        "items": {"createMissing": True},
                        "applications": {"createMissing": True},
                        "graphs": {"createMissing": True},
                        "groups": {"createMissing": True},
                        "templateLinkage": {"createMissing": True},
                        "templates": {"createMissing": True},
                        "triggers": {"createMissing": True},
                    }
                })
                self.zabbix_api.do_request(req)
        except IOError, e:
            print "  " + str(e)
Exemplo n.º 45
0
class zoop:
    """Outermost class for all nested classes"""

    def __init__(self, url=None, username=None, password=None, logLevel=None, logfile=None):
        if not (url and username and password):
            raise zoopError("Valid url, username and password must be passed at instance creation.")
        else:
            self.logconfig(logLevel, logfile)
            self.url = url
            self.username = username
            self.password = password
            # Populate these values in these subclasses so they are filled.
            self.connect()


    def logconfig(self, logLevel, logfile):
        if logfile is None:
            log_hndlr = logging.StreamHandler(sys.stdout)
        else:
            try:
                log_hndlr = logging.FileHandler(logfile)
            except:
                log_hndlr = logging.StreamHandler(sys.stdout)
        self.logger = logging.getLogger("zoop.%s" % self.__class__.__name__)
        self.logger.addHandler(log_hndlr)

        if logLevel is None:
            logLevel = "WARNING"
        self.logger.setLevel(logLevel)


    def connect(self):
        """Do login and fill the inner class API values"""
        self.login()
        self.fillInnerClassesAPI()
    

    def login(self):
        """Do API login"""
        try:
            self.api = ZabbixAPI(server=self.url)
            self.api.login(self.username, self.password)
        except Exception, e:
            raise zoopError("Unable to log in with provided credentials.")
            self.debug(logging.ERROR, "Unable to log in with provided credentials. Error %s" % e.args[0])
class ZbxOperation:
    def __init__(self, url, username, password):
        self.api = ZabbixAPI(server=url)
        self.api.login(username, password)

    def get_trigger_id(self, host_name, trigger_name):
        result = self.api.trigger.get({
            "filter": {
                "host": host_name,
                "name": trigger_name,
             }})
        return result[0]['triggerid']

    def delete_trigger_dependency(self, trigger_id):
        self.api.trigger.deletedependencies({"triggerid": trigger_id})

    def add_trigger_dependency(self, trigger_id, depend_on_id):
        self.api.trigger.adddependencies({"triggerid": trigger_id, "dependsOnTriggerid": depend_on_id})
Exemplo n.º 47
0
class BaseCreator(object):
    """ Base class for Zabbix creator """

    def __init__(self, options):
        self.options = options
        self.server = "http://%s/api_jsonrpc.php " % self.options.server
        self.username = self.options.username
        self.password = self.options.password
        self.zbxLogin()

    def zbxLogin(self):
        self.zapi = ZabbixAPI(server=self.server, log_level=0)
        try:
            self.zapi.login(self.username, self.password)
            print "Zabbix API Version: %s" % self.zapi.api_version()
            print "Logged in: %s" % str(self.zapi.test_login())
        except ZabbixAPIException, e:
            sys.stderr.write(str(e) + "\n")
Exemplo n.º 48
0
def map_create(args):
    #Function creates value maps in Zabbix server via API
    result = False
    value_map = parse_mib(args.mib_file, args.value)
    if args.map_name:
        name = args.map_name
    else:
        name = args.value
    value_map_rq = {
            "name": name,
            "mappings": value_map
    }
    zbx_srv = ZabbixAPI(server = args.server)
    try:
        zbx_srv.login(user = args.user, password = args.password)
        print "Zabbix API Version: %s" % zbx_srv.api_version()
        print "Logged in: %s" % str(zbx_srv.test_login())
    except ZabbixAPIException, e:
        sys.exit(error_parse(e))
Exemplo n.º 49
0
def addHostZabbix(hostname, ipAddr, type):
	
	
	# login to zabbix server
	zapi = ZabbixAPI(server=ZAB_CONF['server'], path="", log_level=6)
	zapi.login(ZAB_CONF['username'], ZAB_CONF['password'])
	# Select win or linux group
	
	if type == 'win-server':
		group_id = ZAB_CONF['win_group_id']
		template_id = ZAB_CONF['win_template_id'] 
	elif type == 'cb-server':
		group_id = ZAB_CONF['lin_group_id']
		template_id = ZAB_CONF['lin_template_id'] 	
		 	
	# Form string for Json request
	string = {'host':hostname,'ip':ipAddr,'dns':'','port':'10050','useip':1}
	string["groups"] = {'groupid': group_id}
	string ["templates"] = {'templateid': template_id}
	# Create host "string"
	createdhost=zapi.host.create(string)
Exemplo n.º 50
0
			menu_graphs['type'] = 'GRAPHID'
			menu_graphs['graphid'] = graphs[graph][0]
			menu_graphs['selected'] = graphs[graph][1]
			host_options.append(menu_graphs)
		menu_hosts['options'] = host_options
		menu_options.append(menu_hosts)
	menu['options'] = menu_options

	doMenu(menu)
	os.system('clear')
	checkScreenGraphs(hostgroupid, hostgroupname, menu)

if  __name__ == "__main__":
	global config

	config_file = './screenbuilder.conf'

	config = Config(config_file)
	config.parse()
	zapi = ZabbixAPI(server=config.zabbix_frontend)

	try:
		print("Connecting to Zabbix API")
		zapi.login(config.zabbix_user, config.zabbix_password)
		print("Connected to Zabbix API Version: %s" % zapi.api_version())
	except ZabbixAPIException, e:
		print("Zabbix API connection failed")
		print("Additional info: %s" % e)
		sys.exit(1)
	main()
myconf.read(authfile)
server=myconf.getoption('server')
username=myconf.getoption('username')
password=myconf.getoption('password')

myconf.read(triggerDict)
trigger_id=myconf.getoption(key)


# change log level according to arguments passed (debug mode or not)
if debugStatus=='check':
	zapi = ZabbixAPI(server=server, path="", log_level=6)
else:
	zapi = ZabbixAPI(server=server, path="", log_level=0)

zapi.login(username, password)

ack_list=zapi.event.get({"acknowledged":[1]})
problem_list=zapi.event.get({"value":[1]})
event_trigger_list=zapi.event.get({"triggerids":[trigger_id]})

# if in debug mode, print JSON results to stdout
if debugStatus=='check':
	print '\nAcknowleged'
	print ack_list
	print '\nValue (1) PROBLEM'
	print problem_list
	print '\nEvent with Trigger %s' % trigger_id
	print event_trigger_list

'''
Exemplo n.º 52
0
Arquivo: api.py Projeto: ieasm/scripts
def start_session(server="http://sla.naukanet.ru/", username="******", password="******"):
    zapi = ZabbixAPI(server=server, path="", log_level=6)
    zapi.login(username, password)
    return zapi
Exemplo n.º 53
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(type='str', required=True, aliases=['url']),
            login_user=dict(type='str', required=True),
            login_password=dict(type='str', required=True, no_log=True),
            proxy_name=dict(type='str', required=True),
            http_login_user=dict(type='str', required=False, default=None),
            http_login_password=dict(type='str', required=False,
                                     default=None, no_log=True),
            validate_certs=dict(type='bool', required=False, default=True),
            status=dict(default="active", choices=['active', 'passive']),
            state=dict(default="present", choices=['present', 'absent']),
            description=dict(type='str', required=False),
            tls_connect=dict(default='no_encryption',
                             choices=['no_encryption', 'PSK', 'certificate']),
            tls_accept=dict(default='no_encryption',
                            choices=['no_encryption', 'PSK', 'certificate']),
            tls_issuer=dict(type='str', required=False, default=None),
            tls_subject=dict(type='str', required=False, default=None),
            tls_psk_identity=dict(type='str', required=False, default=None),
            tls_psk=dict(type='str', required=False, default=None),
            timeout=dict(type='int', default=10),
            interface=dict(type='dict', required=False, default={})
        ),
        supports_check_mode=True
    )

    if not HAS_ZABBIX_API:
        module.fail_json(msg="Missing requried zabbix-api module" +
                             " (check docs or install with:" +
                             " pip install zabbix-api)")

    server_url = module.params['server_url']
    login_user = module.params['login_user']
    login_password = module.params['login_password']
    http_login_user = module.params['http_login_user']
    http_login_password = module.params['http_login_password']
    validate_certs = module.params['validate_certs']
    proxy_name = module.params['proxy_name']
    description = module.params['description']
    status = module.params['status']
    tls_connect = module.params['tls_connect']
    tls_accept = module.params['tls_accept']
    tls_issuer = module.params['tls_issuer']
    tls_subject = module.params['tls_subject']
    tls_psk_identity = module.params['tls_psk_identity']
    tls_psk = module.params['tls_psk']
    state = module.params['state']
    timeout = module.params['timeout']
    interface = module.params['interface']

    # convert enabled to 0; disabled to 1
    status = 6 if status == "passive" else 5

    if tls_connect == 'certificate':
        tls_connect = 4
    elif tls_connect == 'PSK':
        tls_connect = 2
    else:
        tls_connect = 1

    if tls_accept == 'certificate':
        tls_accept = 4
    elif tls_accept == 'PSK':
        tls_accept = 2
    else:
        tls_accept = 1

    zbx = None
    # login to zabbix
    try:
        zbx = ZabbixAPI(server_url, timeout=timeout,
                        user=http_login_user,
                        passwd=http_login_password,
                        validate_certs=validate_certs)
        zbx.login(login_user, login_password)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)

    proxy = Proxy(module, zbx)

    # check if proxy already exists
    proxy_id = proxy.proxy_exists(proxy_name)

    if proxy_id:
        if state == "absent":
            # remove proxy
            proxy.delete_proxy(proxy_id, proxy_name)
        else:
            proxy.update_proxy(proxy_id, {
                'host': proxy_name,
                'description': description,
                'status': str(status),
                'tls_connect': str(tls_connect),
                'tls_accept': str(tls_accept),
                'tls_issuer': tls_issuer,
                'tls_subject': tls_subject,
                'tls_psk_identity': tls_psk_identity,
                'tls_psk': tls_psk,
                'interface': interface
            })
    else:
        if state == "absent":
            # the proxy is already deleted.
            module.exit_json(changed=False)

        proxy_id = proxy.add_proxy(data={
            'host': proxy_name,
            'description': description,
            'status': str(status),
            'tls_connect': str(tls_connect),
            'tls_accept': str(tls_accept),
            'tls_issuer': tls_issuer,
            'tls_subject': tls_subject,
            'tls_psk_identity': tls_psk_identity,
            'tls_psk': tls_psk,
            'interface': interface
        })
Exemplo n.º 54
0
    if not HAS_ZABBIX_API:
        module.fail_json(msg='Missing requried zabbix-api module (check docs or install with: pip install zabbix-api)')

    try:
        login_user = module.params['login_user'] or os.environ['ZABBIX_LOGIN_USER']
        login_password = module.params['login_password'] or os.environ['ZABBIX_LOGIN_PASSWORD']
        server_url = module.params['server_url'] or os.environ['ZABBIX_SERVER_URL']
    except KeyError, e:
        module.fail_json(msg='Missing login data: %s is not set.' % e.message)

    host_group = module.params['host_group']
    state = module.params['state']

    try:
        zbx = ZabbixAPI(server_url)
        zbx.login(login_user, login_password)
    except BaseException as e:
        module.fail_json(msg='Failed to connect to Zabbix server: %s' % e)

    changed = False
    msg = ''

    if state == 'present':
        (rc, exists, error) = check_group(zbx, host_group)
        if rc != 0:
            module.fail_json(msg='Failed to check host group %s existance: %s' % (host_group, error))
        if not exists:
            if module.check_mode:
                changed = True
            else:
                (rc, group, error) = create_group(zbx, host_group)
Exemplo n.º 55
0
# -*- coding: utf-8 -*-
#"""
#Created on Tue Aug 11 22:36:58 2015

#@author: Janssen dos reis lima 
#@email : [email protected] / [email protected]
#@web   : conectsys.com.br / blog.conectsys.com.br

#"""

from zabbix_api import ZabbixAPI

# add the IP of your Zabbix Server
zapi = ZabbixAPI(server="http://<ip_of_server>/zabbix")
# add your access credentials
zapi.login("<user>", "<password>")

def get_hostgroups():
    hostgroups = zapi.hostgroup.get({"output": "extend"})
    listaGrupos = []
    for x in hostgroups:
        print x['name']
        listaGrupos += [x['name']]
    return listaGrupos

def get_hostgroups_id(grupo):
    groupId = zapi.hostgroup.get({"output": "extend","filter":{"name":grupo}})[0]['groupid']
    return groupId

def get_hosts(grupo):
    hosts_grupo = zapi.host.get({"groupids":get_hostgroups_id(grupo),"output":["host"]})
Exemplo n.º 56
-1
def get_host_id(host_name):
    zapi = ZabbixAPI(server='http://127.0.0.1/zabbix')
    zapi.login('svc_monitoria', 'vk98v#m$')
    host_response = zapi.host.get({'filter': {'host': str(host_name.rstrip())}})#[0]['hostid']
    host_id = host_response[0]['hostid']

    return host_id