Exemplo n.º 1
0
def authenticate():
    zapi = ZabbixAPI(server='http://zabbix-server-centos/api_jsonrpc.php')
    zapi.login("Admin", "zabbix")
    return zapi
Exemplo n.º 2
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),
        proxy_address=dict(type='str', required=False),
        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(type='str',
                    default="active",
                    choices=['active', 'passive']),
        state=dict(type='str',
                   default="present",
                   choices=['present', 'absent']),
        description=dict(type='str', required=False),
        tls_connect=dict(type='str',
                         default='no_encryption',
                         choices=['no_encryption', 'PSK', 'certificate']),
        tls_accept=dict(type='str',
                        default='no_encryption',
                        choices=['no_encryption', 'PSK', 'certificate']),
        ca_cert=dict(type='str',
                     required=False,
                     default=None,
                     aliases=['tls_issuer']),
        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_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']
    proxy_name = module.params['proxy_name']
    proxy_address = module.params['proxy_address']
    description = module.params['description']
    status = module.params['status']
    tls_connect = module.params['tls_connect']
    tls_accept = module.params['tls_accept']
    tls_issuer = module.params['ca_cert']
    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)
        atexit.register(zbx.logout)
    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,
                    'proxy_address': proxy_address
                })
    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,
                'proxy_address': proxy_address
            })
Exemplo n.º 3
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),
        timeout=dict(type='int', default=10),
        validate_certs=dict(type='bool', required=False, default=True),
        name=dict(type='str', required=True, aliases=['map_name']),
        data=dict(type='str', required=False, aliases=['dot_data']),
        width=dict(type='int', default=800),
        height=dict(type='int', default=600),
        state=dict(type='str',
                   default="present",
                   choices=['present', 'absent']),
        default_image=dict(type='str', required=False, aliases=['image']),
        margin=dict(type='int', default=40),
        expand_problem=dict(type='bool', default=True),
        highlight=dict(type='bool', default=True),
        label_type=dict(
            type='str',
            default='name',
            choices=['label', 'ip', 'name', 'status', 'nothing', 'custom']),
    ),
                           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)
    if not HAS_PYDOTPLUS:
        module.fail_json(msg=missing_required_lib(
            'pydotplus', url='https://pypi.org/project/pydotplus/'),
                         exception=PYDOT_IMP_ERR)
    if not HAS_WEBCOLORS:
        module.fail_json(msg=missing_required_lib(
            'webcolors', url='https://pypi.org/project/webcolors/'),
                         exception=WEBCOLORS_IMP_ERR)
    if not HAS_PIL:
        module.fail_json(msg=missing_required_lib(
            'Pillow', url='https://pypi.org/project/Pillow/'),
                         exception=PIL_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']
    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)
        atexit.register(zbx.logout)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)

    sysmap = Map(module, zbx)

    if sysmap.state == "absent":
        if sysmap.map_exists():
            sysmap.delete_map()
            module.exit_json(changed=True,
                             result="Successfully deleted map: %s" %
                             sysmap.map_name)
        else:
            module.exit_json(changed=False)
    else:
        map_config = sysmap.get_map_config()
        if sysmap.map_exists():
            if sysmap.is_exist_map_correct(map_config):
                module.exit_json(changed=False)
            else:
                sysmap.update_map(map_config)
                module.exit_json(changed=True,
                                 result="Successfully updated map: %s" %
                                 sysmap.map_name)
        else:
            sysmap.create_map(map_config)
            module.exit_json(changed=True,
                             result="Successfully created map: %s" %
                             sysmap.map_name)
Exemplo n.º 4
0
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 09 18:37:18 2015

@author: Janssen dos Reis Lima

how to use: python ack_event_zabbix.py <event.id>
"""

from zabbix_api import ZabbixAPI
import sys

zabbix_server = "http://<your_server>/zabbix"
username = "******"
password = "******"

zapi = ZabbixAPI(server = zabbix_server)
zapi.login(username, password)

zapi.event.acknowledge({"eventids": sys.argv[1], "message": "Checking the problem."})
Exemplo n.º 5
0
def main():
    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),
                         user_group_name=dict(type='str', required=True),
                         host_groups=dict(
                             type='list',
                             required=False,
                             options=dict(
                                 host_group_name=dict(type='str',
                                                      required=True),
                                 permission=dict(
                                     type='str',
                                     required=True,
                                     choices=['deny', 'read', 'read-write']),
                             )),
                         users=dict(type='list'),
                         state=dict(type='str',
                                    default='present',
                                    required=False,
                                    choices=['present', 'absent']),
                         timeout=dict(type='int', default=10))

    module = AnsibleModule(argument_spec, supports_check_mode=True)

    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']
    user_group_name = module.params['user_group_name']
    users = module.params['users']
    host_groups = module.params['host_groups']
    state = module.params['state']
    timeout = module.params['timeout']

    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)

    host_group_permission = {'deny': 0, 'read': 2, 'read-write': 3}

    result = dict(changed=False)
    if state == "present":
        nested_dict = (lambda: defaultdict(nested_dict))

        r = check_user_group(zbx, user_group_name)
        if (r):
            result.update(r)
            module.exit_json(**result)

        exist_groups = []
        for host_group in host_groups:
            r = get_host_group_id(zbx, host_group['host_group_name'])
            if (r):
                exist_groups.append({
                    'permission':
                    host_group_permission[host_group['permission']],
                    'id':
                    r['groupid']
                })
            else:
                module.fail_json(msg="host group %s not found." %
                                 host_group['host_group_name'])

        user_ids = []
        if (users):
            for user in users:
                r = get_user_id(zbx, user)
                if (r):
                    user_ids.append(r['userid'])
                else:
                    module.fail_json(msg="user %s not found." % user)

        try:
            r = zbx.usergroup.create({
                'name': user_group_name,
                'rights': exist_groups,
                'userids': user_ids
            })
            result['changed'] = True
            result.update(r)
            module.exit_json(**result)
        except Exception as e:
            module.fail_json(msg="Error adding user group %s: %s" %
                             (user_group_name, e))

    if state == "absent":
        r = check_user_group(zbx, user_group_name)
        if (r):
            r = zbx.usergroup.delete([r['usrgrpid']])
            result['changed'] = True
            result.update(r)
            module.exit_json(**result)
        else:
            module.exit_json(**result)
Exemplo n.º 6
0
from zabbix_api import ZabbixAPI
from pprint import pprint
from openpyxl import Workbook

wb = Workbook()
ws = wb.active
ws.title = "DB performce report"
zapi = ZabbixAPI(server="http://mon.marvel.denagames-asia.com/zabbix")
username = '******'
password = '******'

# Header
ws['A1'] = 'Time'
ws['B1'] = '02/04-07/04'
ws['B2'] = 'Max CPU Ulti (%)'
ws['C2'] = 'Avg CPU Ulti (%)'
ws['D2'] = 'Query Per Second'
ws['E2'] = 'Current Instance Type'
ws['F2'] = 'Max Mem Usage (GB)'
ws['G2'] = 'Avg Mem Usage (GB)'
ws['H2'] = 'Max IOPS Data Volume'
ws['I2'] = 'Avg IOPS Data Volume'
ws['J2'] = 'Size Data Volume'
ws['K2'] = 'Usage Data Volume'
ws['L2'] = 'IOPS'
ws['M2'] = 'Max IOPS Log Volume'
ws['N2'] = 'Avg IOPS Log Volume'
ws['O2'] = 'Size Log Volume'
ws['P2'] = 'Usage Log Volume'
ws['Q2'] = 'IOPS'
ws['R2'] = 'Max Traffic Input'
Exemplo n.º 7
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),
        host_name=dict(type='str', required=True),
        macro_name=dict(type='str', required=True),
        macro_value=dict(type='str', required=False),
        state=dict(type='str',
                   default='present',
                   choices=['present', 'absent']),
        timeout=dict(type='int', default=10),
        force=dict(type='bool', default=True)),
                           required_if=[['state', 'present', ['macro_value']]],
                           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']
    host_name = module.params['host_name']
    macro_name = normalize_macro_name(module.params['macro_name'])
    macro_value = module.params['macro_value']
    state = module.params['state']
    timeout = module.params['timeout']
    force = module.params['force']

    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_macro_class_obj = HostMacro(module, zbx)

    if host_name:
        host_id = host_macro_class_obj.get_host_id(host_name)
        host_macro_obj = host_macro_class_obj.get_host_macro(
            macro_name, host_id)

    if state == 'absent':
        if not host_macro_obj:
            module.exit_json(changed=False,
                             msg="Host Macro %s does not exist" % macro_name)
        else:
            # delete a macro
            host_macro_class_obj.delete_host_macro(host_macro_obj, macro_name)
    else:
        if not host_macro_obj:
            # create host macro
            host_macro_class_obj.create_host_macro(macro_name, macro_value,
                                                   host_id)
        elif force:
            # update host macro
            host_macro_class_obj.update_host_macro(host_macro_obj, macro_name,
                                                   macro_value)
        else:
            module.exit_json(
                changed=False,
                result="Host macro %s already exists and force is set to no" %
                macro_name)
Exemplo n.º 8
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),
        screens=dict(type='list',
                     elements='dict',
                     required=True,
                     options=dict(
                         screen_name=dict(type='str', required=True),
                         host_group=dict(type='str'),
                         state=dict(type='str',
                                    default='present',
                                    choices=['absent', 'present']),
                         graph_names=dict(type='list', elements='str'),
                         graph_width=dict(type='int', default=None),
                         graph_height=dict(type='int', default=None),
                         graphs_in_row=dict(type='int', default=3),
                         sort=dict(default=False, type='bool'),
                     ),
                     required_if=[['state', 'present', ['host_group']]])),
                           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']
    timeout = module.params['timeout']
    screens = module.params['screens']

    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)

    screen = Screen(module, zbx)
    created_screens = []
    changed_screens = []
    deleted_screens = []

    for zabbix_screen in screens:
        screen_name = zabbix_screen['screen_name']
        screen_id = screen.get_screen_id(screen_name)
        state = zabbix_screen['state']
        sort = zabbix_screen['sort']

        if state == "absent":
            if screen_id:
                screen_item_list = screen.get_screen_items(screen_id)
                screen_item_id_list = []
                for screen_item in screen_item_list:
                    screen_item_id = screen_item['screenitemid']
                    screen_item_id_list.append(screen_item_id)
                screen.delete_screen_items(screen_id, screen_item_id_list)
                screen.delete_screen(screen_id, screen_name)

                deleted_screens.append(screen_name)
        else:
            host_group = zabbix_screen['host_group']
            graph_names = zabbix_screen['graph_names']
            graphs_in_row = zabbix_screen['graphs_in_row']
            graph_width = zabbix_screen['graph_width']
            graph_height = zabbix_screen['graph_height']
            host_group_id = screen.get_host_group_id(host_group)
            hosts = screen.get_host_ids_by_group_id(host_group_id, sort)

            screen_item_id_list = []
            resource_id_list = []

            graph_ids, v_size = screen.get_graph_ids(hosts, graph_names)
            h_size, v_size = screen.get_hsize_vsize(hosts, v_size,
                                                    graphs_in_row)

            if not screen_id:
                # create screen
                screen_id = screen.create_screen(screen_name, h_size, v_size)
                screen.create_screen_items(screen_id, hosts, graph_names,
                                           graph_width, graph_height, h_size,
                                           graphs_in_row)
                created_screens.append(screen_name)
            else:
                screen_item_list = screen.get_screen_items(screen_id)

                for screen_item in screen_item_list:
                    screen_item_id = screen_item['screenitemid']
                    resource_id = screen_item['resourceid']
                    screen_item_id_list.append(screen_item_id)
                    resource_id_list.append(resource_id)

                # when the screen items changed, then update
                if graph_ids != resource_id_list:
                    deleted = screen.delete_screen_items(
                        screen_id, screen_item_id_list)
                    if deleted:
                        screen.update_screen(screen_id, screen_name, h_size,
                                             v_size)
                        screen.create_screen_items(screen_id, hosts,
                                                   graph_names, graph_width,
                                                   graph_height, h_size,
                                                   graphs_in_row)
                        changed_screens.append(screen_name)

    if created_screens and changed_screens:
        module.exit_json(
            changed=True,
            result=
            "Successfully created screen(s): %s, and updated screen(s): %s" %
            (",".join(created_screens), ",".join(changed_screens)))
    elif created_screens:
        module.exit_json(changed=True,
                         result="Successfully created screen(s): %s" %
                         ",".join(created_screens))
    elif changed_screens:
        module.exit_json(changed=True,
                         result="Successfully updated screen(s): %s" %
                         ",".join(changed_screens))
    elif deleted_screens:
        module.exit_json(changed=True,
                         result="Successfully deleted screen(s): %s" %
                         ",".join(deleted_screens))
    else:
        module.exit_json(changed=False)
Exemplo n.º 9
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from zabbix_api import ZabbixAPI
import csv
import sys
import json

# Variaveis
server = sys.argv[1]  #ip-do-zabbix
username = sys.argv[2]  #usuario
password = sys.argv[3]  #senha
arquivo = sys.argv[4]

# Loga no Zabbix Server
zapi = ZabbixAPI(server=server, path="")
zapi.login(username, password)

# Le o arquivo CSV
# Formato do CSV:
# Hostgroup;Template;Hostname;Visible name;DNS;IP;Agent type;Connect to;Proxy;Inventory;Macros
f = csv.reader(
    open(arquivo),
    delimiter=';')  #lendo-a-lista de host e separando pelo delimatador ';'

for [
        hostgroup, template, hostname, alias, dns, ip, agent, connectto, proxy,
        inventory, macros
] in f:

    print "+ Cadastrando o host " + hostname
Exemplo n.º 10
0
#!/usr/bin/env python
#-*-coding: utf-8-*-
from zabbix_api import ZabbixAPI
zapi=ZabbixAPI(server="SITE")
#Conexão com Zabbix Server
zapi.login("Login","Senha")
#Versao do Zabbix 
print "Version Zabbix:", zapi.api_version()
#Printa os hosts 
hosts = zapi.host.get({"output": "extend", "sortfield": "name"})
for x in hosts:
    print x['available'], "-", x['hostid'], "-", x['name']
#Printa os Triggers
trigger = zapi.trigger.get(only_true=1,
                            skipDependent=1,
                            monitored=1,
                            active=1,
                            output='extend',
                            expandDescription=1,
                            selectHosts=['host'],
                            )


for y in trigger:
	print y['description'], "--", y['host']
#Print UPTIME
uptime = zapi.item.get({'output': "extend", 'hostids': 10084, 'search': {'key_':'system.uptime'}})
print "Tempo",uptime[0]['lastvalue']
trigger = zapi.trigger.get[{'output': "extend", 'group': "HSM"}]
print "Triggers",trigger
Exemplo n.º 11
0
'''
Conta o numero de vezes que o alerta foi disparado
Com esse mesmo metado, podemos verificar quantas vezes
o agent foi disparado, basta trocar o ssh port agent
'''

from zabbix_api import ZabbixAPI

zapi = ZabbixAPI(server="http://localhost/zabbix")
zapi.login("admin","zabbix")

alerts = zapi.alert.get({
	"output": "extend",
	"search": {
		"messages": "ssh"
	},
	"actionsids": "7",
	"countOutput": "True",
})

echo "Executou print"
print("Numero de vezes que a acao foi disparada {0}".format(alerts))
Exemplo n.º 12
0
    # if not up to day update and exit
    exit(0)

#Define zabbix config file

zbx_conf_file = os.path.dirname(
    os.path.realpath(__file__)) + '/../conf/zabbix.conf'

# Get zabbix server connect credentials
for tmp_line in open(zbx_conf_file):
    if "server" in tmp_line: zbx_server = str(tmp_line.split("=")[1]).rstrip()
    if "user" in tmp_line: zbx_user = str(tmp_line.split("=")[1]).rstrip()
    if "pass" in tmp_line: zbx_pass = str(tmp_line.split("=")[1]).rstrip()

# Connect to zabbix server
zapi = ZabbixAPI(zbx_server)
zapi.login(zbx_user, zbx_pass)

parser = argparse.ArgumentParser(description='Arguments to web test in zabbix')
parser.add_argument('--url',
                    required=True,
                    action='store',
                    default=None,
                    dest='url',
                    help='Site url. Example: http://test.com')
parser.add_argument('--pattern',
                    required=True,
                    action='store',
                    default=None,
                    dest='pattern',
                    help='Required pattern on site ')
Exemplo n.º 13
0
import json
import requests
from zabbix_api import ZabbixAPI
from .phpipam import phpipamAPI
teste = phpipamAPI()
teste.api_url()


api_server = 'https://compos-zabbix.compos.com.br'
api_user = '******'
api_password = '******'

#Instanciando a API
zapi = ZabbixAPI(server = api_server, path="", log_level=6)
zapi.login(api_user, api_password)

hosts = zapi.host.get({"output": hostgroup)
print(len(hosts))
Exemplo n.º 14
0
# -*- coding: utf-8 -*-

from zabbix_api import ZabbixAPI
import datetime
import sys
import re

URLZABBIX = ""
USUARIO = ""
SENHA = ""
GRUPO = ""

zapi = ZabbixAPI(server=URLZABBIX)
zapi.login(USUARIO, SENHA)

print("===================== LISTA DOS INCIDENTES ====================")
print(datetime.datetime.now())

grupoX = zapi.hostgroup.get({
    "output": ["id"],
    "search": {
        "name": [GRUPO],
    },
    "searchWildcardsEnabled": True,
})

id = grupoX[0]['groupid']

eventos = zapi.problem.get({
    "output": [
        "eventids",
Exemplo n.º 15
0
try:
    with open('/opt/zaas/bin/zabbix_api_pass.py'):
        sys.path.insert(0, './')
        import zabbix_api_pass
except IOError:
    print 'You must create the zabbix_api_pass.py password file, like this:\npassword=\"xxxxxx\"\n\n'

logging.basicConfig(filename="/var/log/zaas.log",
                    format=LOG_FORMAT,
                    level=logging.DEBUG)
zabbix_server = "monitoracao.stg.intra"
urlpath = "/zabbix"
server = "http://" + zabbix_server + urlpath
username = "******"
zapi = ZabbixAPI(server=server, path="", log_level=0)
zapi.login(username, zabbix_api_pass.password)
r_server = redis.Redis("redis-server.intra")


def reply_json(f):
    @wraps(f)
    def json_dumps(*args, **kwargs):
        r = f(*args, **kwargs)
        if r and type(r) in (dict, list, tuple, str, unicode):
            response.content_type = "application/json; charset=UTF-8"
            return dumps(r)
        return r

    return json_dumps
Exemplo n.º 16
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),
        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_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']
    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,
                        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)

    hostGroup = HostGroup(module, zbx)

    group_ids = []
    group_list = []
    if host_groups:
        group_ids, group_list = hostGroup.get_group_ids(host_groups)

    if state == "absent":
        # delete host groups
        if group_ids:
            delete_group_names = []
            hostGroup.delete_host_group(group_ids)
            for group in group_list:
                delete_group_names.append(group['name'])
            module.exit_json(changed=True,
                             result="Successfully deleted host group(s): %s." %
                             ",".join(delete_group_names))
        else:
            module.exit_json(changed=False,
                             result="No host group(s) to delete.")
    else:
        # create host groups
        group_add_list = hostGroup.create_host_group(host_groups)
        if len(group_add_list) > 0:
            module.exit_json(changed=True,
                             result="Successfully created host group(s): %s" %
                             group_add_list)
        else:
            module.exit_json(changed=False)
            "triggervalue": triggervalue,
            "triggername": triggername,
            "applicationname": triggerapplicationname,
            "hostname": host_name,
            "itemid": triggeritemid
        },
    )


if __name__ == '__main__':

    # Initialize external parameters
    cf = ConfigParser.ConfigParser()
    cf.read("get_zabbix_info.conf")
    hostnames = ast.literal_eval(cf.get("host", "hostnames"))
    zapi = ZabbixAPI(server=cf.get("server", "serveraddress"))
    zapi.login(cf.get("userconfig", "user"), cf.get("userconfig", "password"))

    for hostname in hostnames:
        hostid = get_host_id(hostname)
        triggerinfos = get_trigger_list_info(hostid)

        for triggerinfo in triggerinfos:
            info_triggerid = triggerinfo[0]
            info_triggervalue = triggerinfo[1]
            info_triggername = triggerinfo[2]
            info_triggeritemid = triggerinfo[3]
            info_triggerapplicationname = triggerinfo[4]
            update_mysql(info_triggerid, info_triggervalue, info_triggername,
                         info_triggerapplicationname[0], info_triggeritemid,
                         hostname)
Exemplo n.º 18
0
    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:
Exemplo n.º 19
0
# ----------------------------------------------------------
# 			Script start
# ----------------------------------------------------------

# read the configuration file from to the dictionary settings
try:
    settings = read_config('facility-monitoring.cfg')
except:
    sys.stderr.write("ERROR: Can not read file facility-monitoring.cfg.\n")
    sys.exit()

logger = init_logger(settings, 'facility-monitoring.py')

try:
    zabbix_server_uri = settings['localserver']
    zapi = ZabbixAPI(server=zabbix_server_uri,
                     log_level=int(settings['log_level']))

    zabbix_username = settings['username']
    zabbix_password = settings['password']
    zapi.login(zabbix_username, zabbix_password)

    hosttmp = zapi.host.get({
        "filter": {
            "host": "FITeagle-Zabbix-Server"
        },
        "output": "extend"
    })

    hostid = hosttmp.pop()['hostid']
    itemid_Fiteagle = zapi.item.get({
        "output": "extend",
Exemplo n.º 20
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),
        host_name=dict(type='str', default='', required=False),
        host_ip=dict(type='list', default=[], required=False),
        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),
        exact_match=dict(type='bool', required=False, default=False),
        remove_duplicate=dict(type='bool', required=False, default=True),
        host_inventory=dict(type='list', default=[], required=False)),
                           supports_check_mode=True)
    if module._name == 'zabbix_host_facts':
        module.deprecate(
            "The 'zabbix_host_facts' module has been renamed to 'zabbix_host_info'",
            version='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']
    host_name = module.params['host_name']
    host_ips = module.params['host_ip']
    timeout = module.params['timeout']
    exact_match = module.params['exact_match']
    is_remove_duplicate = module.params['remove_duplicate']
    host_inventory = module.params['host_inventory']

    if not host_inventory:
        host_inventory = 'extend'

    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)

    if host_name:
        hosts = host.get_hosts_by_host_name(host_name, exact_match,
                                            host_inventory)
        if is_remove_duplicate:
            hosts = host.delete_duplicate_hosts(hosts)
        extended_hosts = []
        for zabbix_host in hosts:
            zabbix_host['hostinterfaces'] = host._zapi.hostinterface.get({
                'output':
                'extend',
                'hostids':
                zabbix_host['hostid']
            })
            extended_hosts.append(zabbix_host)
        module.exit_json(ok=True, hosts=extended_hosts)

    elif host_ips:
        extended_hosts = host.get_hosts_by_ip(host_ips, host_inventory)
        if is_remove_duplicate:
            hosts = host.delete_duplicate_hosts(extended_hosts)
        module.exit_json(ok=True, hosts=extended_hosts)
    else:
        module.exit_json(ok=False, hosts=[], result="No Host present")
Exemplo n.º 21
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),
        name=dict(type='str', required=True),
        parent=dict(type='str', required=False),
        sla=dict(type='float', required=False),
        calculate_sla=dict(type='bool', required=False, default=False),
        algorithm=dict(default='one_child',
                       required=False,
                       choices=['no', 'one_child', 'all_children']),
        trigger_name=dict(type='str', required=False),
        trigger_host=dict(type='str', required=False),
        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_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']
    name = module.params['name']
    parent = module.params['parent']
    sla = module.params['sla']
    calculate_sla = module.params['calculate_sla']
    algorithm = module.params['algorithm']
    trigger_name = module.params['trigger_name']
    trigger_host = module.params['trigger_host']
    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,
                        validate_certs=validate_certs)
        zbx.login(login_user, login_password)
        atexit.register(zbx.logout)
    except ZabbixAPIException as error:
        module.fail_json(msg="Failed to connect to Zabbix server: %s" % error)

    # Load service module
    service = Service(module, zbx)
    service_ids = service.get_service_ids(name)
    if service_ids:
        service_json = service.dump_services(service_ids)

    # Delete service
    if state == "absent":
        if not service_ids:
            module.exit_json(changed=False,
                             msg="Service not found, no change: %s" % name)
        service.delete_service(service_ids)
        module.exit_json(changed=True,
                         result="Successfully deleted service(s) %s" % name)

    elif state == "present":
        if (trigger_name and not trigger_host) or (trigger_host
                                                   and not trigger_name):
            module.fail_json(
                msg=
                "Specify either both trigger_host and trigger_name or none to create or update a service"
            )
        # Does not exists going to create it
        if not service_ids:
            service.create_service(name, parent, sla, calculate_sla,
                                   trigger_name, trigger_host, algorithm)
            module.exit_json(changed=True, msg="Service %s created" % name)
        # Else we update it if needed
        else:
            service.update_service(service_ids[0], name, parent, sla,
                                   calculate_sla, trigger_name, trigger_host,
                                   algorithm)
def main():
    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),
        name=dict(type='str', required=True),
        state=dict(type='str', default='present', choices=['present', 'absent']),
        type=dict(type='str', choices=['email', 'script', 'sms', 'jabber', 'ez_texting'], required=True),
        status=dict(type='str', default='enabled', choices=['enabled', 'disabled'], required=False),
        max_sessions=dict(type='int', default=1, required=False),
        max_attempts=dict(type='int', default=3, required=False),
        attempt_interval=dict(type='int', default=10, required=False),
        # Script
        script_name=dict(type='str', required=False),
        script_params=dict(type='list', required=False),
        # SMS
        gsm_modem=dict(type='str', required=False),
        # Jabber
        username=dict(type='str', required=False),
        password=dict(type='str', required=False, no_log=True),
        # Email
        smtp_server=dict(type='str', default='localhost', required=False),
        smtp_server_port=dict(type='int', default=25, required=False),
        smtp_helo=dict(type='str', default='localhost', required=False),
        smtp_email=dict(type='str', required=False),
        smtp_security=dict(type='str', required=False, choices=['None', 'STARTTLS', 'SSL/TLS']),
        smtp_authentication=dict(type='bool', default=False, required=False),
        smtp_verify_host=dict(type='bool', default=False, required=False),
        smtp_verify_peer=dict(type='bool', default=False, required=False),
        # EZ Text
        message_text_limit=dict(type='str', required=False, choices=['USA', 'Canada'])
    )

    required_params = [
        ['type', 'email', ['smtp_email']],
        ['type', 'script', ['script_name']],
        ['type', 'sms', ['gsm_modem']],
        ['type', 'jabber', ['username', 'password']],
        ['type', 'ez_texting', ['username', 'password', 'message_text_limit']],
        ['smtp_authentication', True, ['username', 'password']]
    ]

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True
    )

    if module.params['state'] == 'present':
        validate_params(module, required_params)

    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']
    state = module.params['state']
    timeout = module.params['timeout']
    name = module.params['name']
    transport_type = module.params['type']
    status = module.params['status']
    max_sessions = module.params['max_sessions']
    max_attempts = module.params['max_attempts']
    attempt_interval = module.params['attempt_interval']
    # Script
    script_name = module.params['script_name']
    script_params = module.params['script_params']
    # SMS
    gsm_modem = module.params['gsm_modem']
    # Jabber
    username = module.params['username']
    password = module.params['password']
    # Email
    smtp_server = module.params['smtp_server']
    smtp_server_port = module.params['smtp_server_port']
    smtp_helo = module.params['smtp_helo']
    smtp_email = module.params['smtp_email']
    smtp_security = module.params['smtp_security']
    smtp_authentication = module.params['smtp_authentication']
    smtp_verify_host = module.params['smtp_verify_host']
    smtp_verify_peer = module.params['smtp_verify_peer']
    # EZ Text
    message_text_limit = module.params['message_text_limit']

    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)

    mediatype_exists, mediatype_id = check_if_mediatype_exists(module, zbx, name)

    parameters = construct_parameters(
        name=name,
        transport_type=transport_type,
        status=status,
        max_sessions=max_sessions,
        max_attempts=max_attempts,
        attempt_interval=attempt_interval,
        script_name=script_name,
        script_params=script_params,
        gsm_modem=gsm_modem,
        username=username,
        password=password,
        smtp_server=smtp_server,
        smtp_server_port=smtp_server_port,
        smtp_helo=smtp_helo,
        smtp_email=smtp_email,
        smtp_security=smtp_security,
        smtp_authentication=smtp_authentication,
        smtp_verify_host=smtp_verify_host,
        smtp_verify_peer=smtp_verify_peer,
        message_text_limit=message_text_limit
    )

    if mediatype_exists:
        if state == 'absent':
            if module.check_mode:
                module.exit_json(
                    changed=True,
                    msg="Mediatype would have been deleted. Name: {name}, ID: {_id}".format(
                        name=name,
                        _id=mediatype_id
                    )
                )
            mediatype_id = delete_mediatype(module, zbx, mediatype_id)
            module.exit_json(
                changed=True,
                msg="Mediatype deleted. Name: {name}, ID: {_id}".format(
                    name=name,
                    _id=mediatype_id
                )
            )
        else:
            params_to_update, diff = get_update_params(module, zbx, mediatype_id, **parameters)
            if params_to_update == {}:
                module.exit_json(
                    changed=False,
                    msg="Mediatype is up to date: {name}".format(name=name)
                )
            else:
                if module.check_mode:
                    module.exit_json(
                        changed=True,
                        diff=diff,
                        msg="Mediatype would have been updated. Name: {name}, ID: {_id}".format(
                            name=name,
                            _id=mediatype_id
                        )
                    )
                mediatype_id = update_mediatype(
                    module, zbx,
                    mediatypeid=mediatype_id,
                    **params_to_update
                )
                module.exit_json(
                    changed=True,
                    diff=diff,
                    msg="Mediatype updated. Name: {name}, ID: {_id}".format(
                        name=name,
                        _id=mediatype_id
                    )
                )
    else:
        if state == "absent":
            module.exit_json(changed=False)
        else:
            if module.check_mode:
                module.exit_json(
                    changed=True,
                    msg="Mediatype would have been created. Name: {name}, ID: {_id}".format(
                        name=name,
                        _id=mediatype_id
                    )
                )
            mediatype_id = create_mediatype(module, zbx, **parameters)
            module.exit_json(
                changed=True,
                msg="Mediatype created: {name}, ID: {_id}".format(
                    name=name,
                    _id=mediatype_id
                )
            )
Exemplo n.º 23
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),
            template_name=dict(type='str', required=False),
            template_json=dict(type='json', required=False),
            template_xml=dict(type='str', required=False),
            template_groups=dict(type='list', required=False),
            link_templates=dict(type='list', required=False),
            clear_templates=dict(type='list', required=False),
            macros=dict(type='list', required=False),
            dump_format=dict(type='str', required=False, default='json', choices=['json', 'xml']),
            state=dict(type='str', default="present", choices=['present', 'absent', 'dump']),
            timeout=dict(type='int', default=10)
        ),
        required_one_of=[
            ['template_name', 'template_json', 'template_xml']
        ],
        mutually_exclusive=[
            ['template_name', 'template_json', 'template_xml']
        ],
        required_if=[
            ['state', 'absent', ['template_name']],
            ['state', 'dump', ['template_name']]
        ],
        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']
    template_name = module.params['template_name']
    template_json = module.params['template_json']
    template_xml = module.params['template_xml']
    template_groups = module.params['template_groups']
    link_templates = module.params['link_templates']
    clear_templates = module.params['clear_templates']
    template_macros = module.params['macros']
    dump_format = module.params['dump_format']
    state = module.params['state']
    timeout = module.params['timeout']

    zbx = None
    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 ZabbixAPIException as e:
        module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)

    template = Template(module, zbx)

    # Identify template names for IDs retrieval
    # Template names are expected to reside in ['zabbix_export']['templates'][*]['template'] for both data types
    template_content, template_type = None, None
    if template_json is not None:
        template_type = 'json'
        template_content = template_json
        json_parsed = template.load_json_template(template_content)
        template_names = list(t['template'] for t in json_parsed['zabbix_export']['templates'])

    elif template_xml is not None:
        template_type = 'xml'
        template_content = template_xml
        xml_parsed = template.load_xml_template(template_content)
        template_names = list(t.find('template').text for t in list(xml_parsed.find('templates')))

    else:
        template_names = [template_name]

    template_ids = template.get_template_ids(template_names)

    if state == "absent":
        if not template_ids:
            module.exit_json(changed=False, msg="Template not found. No changed: %s" % template_name)

        template.delete_template(template_ids)
        module.exit_json(changed=True, result="Successfully deleted template %s" % template_name)

    elif state == "dump":
        module.deprecate("The 'dump' state has been deprecated and will be removed, use 'zabbix_template_info' module instead.", version='2.14')
        if not template_ids:
            module.fail_json(msg='Template not found: %s' % template_name)

        if dump_format == 'json':
            module.exit_json(changed=False, template_json=template.dump_template(template_ids, template_type='json'))
        elif dump_format == 'xml':
            module.exit_json(changed=False, template_xml=template.dump_template(template_ids, template_type='xml'))

    elif state == "present":
        # Load all subelements for template that were provided by user
        group_ids = None
        if template_groups is not None:
            group_ids = template.get_group_ids_by_group_names(template_groups)

        link_template_ids = None
        if link_templates is not None:
            link_template_ids = template.get_template_ids(link_templates)

        clear_template_ids = None
        if clear_templates is not None:
            clear_template_ids = template.get_template_ids(clear_templates)

        if template_macros is not None:
            # Zabbix configuration.export does not differentiate python types (numbers are returned as strings)
            for macroitem in template_macros:
                for key in macroitem:
                    macroitem[key] = str(macroitem[key])

        if not template_ids:
            # Assume new templates are being added when no ID's were found
            if template_content is not None:
                template.import_template(template_content, template_type)
                module.exit_json(changed=True, result="Template import successful")

            else:
                if group_ids is None:
                    module.fail_json(msg='template_groups are required when creating a new Zabbix template')

                template.add_template(template_name, group_ids, link_template_ids, template_macros)
                module.exit_json(changed=True, result="Successfully added template: %s" % template_name)

        else:
            changed = template.check_template_changed(template_ids, template_groups, link_templates, clear_templates,
                                                      template_macros, template_content, template_type)

            if module.check_mode:
                module.exit_json(changed=changed)

            if changed:
                if template_type is not None:
                    template.import_template(template_content, template_type)
                else:
                    template.update_template(template_ids, group_ids, link_template_ids, clear_template_ids,
                                             template_macros)

            module.exit_json(changed=changed, result="Template successfully updated")
Exemplo n.º 24
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),
            name=dict(type='str', default=''),
            surname=dict(type='str', default=''),
            usrgrps=dict(type='list', required=True),
            passwd=dict(type='str', required=True, no_log=True),
            override_passwd=dict(type='bool', required=False, default=False),
            lang=dict(type='str', default='en_GB', choices=['en_GB', 'en_US', 'zh_CN', 'cs_CZ', 'fr_FR',
                                                            'he_IL', 'it_IT', 'ko_KR', 'ja_JP', 'nb_NO',
                                                            'pl_PL', 'pt_BR', 'pt_PT', 'ru_RU', 'sk_SK',
                                                            'tr_TR', 'uk_UA']),
            theme=dict(type='str', default='default', choices=['default', 'blue-theme', 'dark-theme']),
            autologin=dict(type='bool', default=False),
            autologout=dict(type='str', default='0'),
            refresh=dict(type='str', default='30'),
            rows_per_page=dict(type='str', default='50'),
            after_login_url=dict(type='str', default=''),
            user_medias=dict(type='list', default=[],
                             elements='dict',
                             options=dict(
                                 mediatype=dict(type='str', default='Email'),
                                 sendto=dict(type='str', required=True),
                                 period=dict(type='str', default='1-7,00:00-24:00'),
                                 severity=dict(type='dict',
                                               options=dict(
                                                   not_classified=dict(type='bool', default=True),
                                                   information=dict(type='bool', default=True),
                                                   warning=dict(type='bool', default=True),
                                                   average=dict(type='bool', default=True),
                                                   high=dict(type='bool', default=True),
                                                   disaster=dict(type='bool', default=True)),
                                               default=dict(
                                                   not_classified=True,
                                                   information=True,
                                                   warning=True,
                                                   average=True,
                                                   high=True,
                                                   disaster=True
                                               )),
                                 active=dict(type='bool', default=True)
            )),
            type=dict(type='str', default='Zabbix user', choices=['Zabbix user', 'Zabbix admin', 'Zabbix super admin']),
            state=dict(type='str', 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_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']
    name = module.params['name']
    surname = module.params['surname']
    usrgrps = module.params['usrgrps']
    passwd = module.params['passwd']
    override_passwd = module.params['override_passwd']
    lang = module.params['lang']
    theme = module.params['theme']
    autologin = module.params['autologin']
    autologout = module.params['autologout']
    refresh = module.params['refresh']
    rows_per_page = module.params['rows_per_page']
    after_login_url = module.params['after_login_url']
    user_medias = module.params['user_medias']
    user_type = module.params['type']
    state = module.params['state']
    timeout = module.params['timeout']

    if autologin:
        autologin = '******'
    else:
        autologin = '******'

    user_type_dict = {
        'Zabbix user': '******',
        'Zabbix admin': '2',
        'Zabbix super admin': '3'
    }
    user_type = user_type_dict[user_type]

    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 state == 'present':
        user_group_ids = user.get_usergroupid_by_user_group_name(usrgrps)
        if zbx_user:
            diff_check_result, diff_params = user.user_parameter_difference_check(zbx_user, alias, name, surname,
                                                                                  user_group_ids, passwd, lang, theme,
                                                                                  autologin, autologout, refresh,
                                                                                  rows_per_page, after_login_url,
                                                                                  user_medias, user_type,
                                                                                  zbx_api_version, override_passwd)

            if not module.check_mode and diff_check_result:
                user_ids = user.update_user(zbx_user, alias, name, surname, user_group_ids, passwd, lang,
                                            theme, autologin, autologout, refresh, rows_per_page, after_login_url,
                                            user_medias, user_type, zbx_api_version, override_passwd)
        else:
            diff_check_result = True
            user_ids, diff_params = user.add_user(alias, name, surname, user_group_ids, passwd, lang, theme, autologin,
                                                  autologout, refresh, rows_per_page, after_login_url, user_medias,
                                                  user_type)

    if state == 'absent':
        if zbx_user:
            diff_check_result = True
            user_ids, diff_params = user.delete_user(zbx_user, alias)
        else:
            diff_check_result = False
            diff_params = {}

    if not module.check_mode:
        if user_ids:
            module.exit_json(changed=True, user_ids=user_ids)
        else:
            module.exit_json(changed=False)
    else:
        if diff_check_result:
            module.exit_json(changed=True, diff=diff_params)
        else:
            module.exit_json(changed=False, diff=diff_params)
Exemplo n.º 25
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            state=dict(required=False,
                       default='present',
                       choices=['present', 'absent']),
            server_url=dict(required=True, default=None, aliases=['url']),
            host_names=dict(type='list',
                            required=False,
                            default=None,
                            aliases=['host_name']),
            minutes=dict(type='int', required=False, default=10),
            host_groups=dict(type='list',
                             required=False,
                             default=None,
                             aliases=['host_group']),
            login_user=dict(required=True, default=None),
            login_password=dict(required=True, default=None),
            name=dict(required=True, default=None),
            desc=dict(required=False, default="Created by Ansible"),
            collect_data=dict(type='bool', required=False, default=True),
        ),
        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)"
        )

    host_names = module.params['host_names']
    host_groups = module.params['host_groups']
    state = module.params['state']
    login_user = module.params['login_user']
    login_password = module.params['login_password']
    minutes = module.params['minutes']
    name = module.params['name']
    desc = module.params['desc']
    server_url = module.params['server_url']
    collect_data = module.params['collect_data']
    if collect_data:
        maintenance_type = 0
    else:
        maintenance_type = 1

    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

    if state == "present":

        now = datetime.datetime.now()
        start_time = time.mktime(now.timetuple())
        period = 60 * int(minutes)  # N * 60 seconds

        if host_groups:
            (rc, group_ids, error) = get_group_ids(zbx, host_groups)
            if rc != 0:
                module.fail_json(msg="Failed to get group_ids: %s" % error)
        else:
            group_ids = []

        if host_names:
            (rc, host_ids, error) = get_host_ids(zbx, host_names)
            if rc != 0:
                module.fail_json(msg="Failed to get host_ids: %s" % error)
        else:
            host_ids = []

        (rc, exists, error) = check_maintenance(zbx, name)
        if rc != 0:
            module.fail_json(
                msg="Failed to check maintenance %s existance: %s" %
                (name, error))

        if not exists:
            if not host_names and not host_groups:
                module.fail_json(
                    msg=
                    "At least one host_name or host_group must be defined for each created maintenance."
                )

            if module.check_mode:
                changed = True
            else:
                (rc, _, error) = create_maintenance(zbx, group_ids, host_ids,
                                                    start_time,
                                                    maintenance_type, period,
                                                    name, desc)
                if rc == 0:
                    changed = True
                else:
                    module.fail_json(msg="Failed to create maintenance: %s" %
                                     error)

    if state == "absent":

        (rc, exists, error) = check_maintenance(zbx, name)
        if rc != 0:
            module.fail_json(
                msg="Failed to check maintenance %s existance: %s" %
                (name, error))

        if exists:
            (rc, maintenance, error) = get_maintenance_id(zbx, name)
            if rc != 0:
                module.fail_json(msg="Failed to get maintenance id: %s" %
                                 error)

            if maintenance:
                if module.check_mode:
                    changed = True
                else:
                    (rc, _, error) = delete_maintenance(zbx, maintenance)
                    if rc == 0:
                        changed = True
                    else:
                        module.fail_json(
                            msg="Failed to remove maintenance: %s" % error)

    module.exit_json(changed=changed)
Exemplo n.º 26
0
#####################################################
#  Ativar / Desativar host
#####################################################

# importando a class zabbix-api
from zabbix_api import ZabbixAPI
import config

zapi = ZabbixAPI(server=config.url)
zapi.login(config.login, config.passwd)

hosts = zapi.host.update({"hostid": "000000", "status": "1"})  # DESATIVAR
hosts = zapi.host.update({"hostid": "000000", "status": "0"})  # ATIVAR
Exemplo n.º 27
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),
            template_name=dict(type='str', required=True),
            template_json=dict(type='json', required=False),
            template_groups=dict(type='list', required=False),
            link_templates=dict(type='list', required=False),
            clear_templates=dict(type='list', required=False),
            macros=dict(type='list', required=False),
            state=dict(default="present", choices=['present', 'absent',
                                                   'dump']),
            timeout=dict(type='int', default=10)
        ),
        supports_check_mode=True
    )

    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']
    template_name = module.params['template_name']
    template_json = module.params['template_json']
    template_groups = module.params['template_groups']
    link_templates = module.params['link_templates']
    clear_templates = module.params['clear_templates']
    template_macros = module.params['macros']
    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, validate_certs=validate_certs)
        zbx.login(login_user, login_password)
    except ZabbixAPIException as e:
        module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)

    template = Template(module, zbx)
    template_ids = template.get_template_ids([template_name])
    existing_template_json = None
    if template_ids:
        existing_template_json = template.dump_template(template_ids)

    # delete template
    if state == "absent":
        # if template not found. no change, no fail
        if not template_ids:
            module.exit_json(changed=False,
                             msg="Template not found. " +
                                 "No changed: %s" % template_name)
        template.delete_template(template_ids)
        module.exit_json(changed=True,
                         result="Successfully delete template %s" %
                         template_name)

    elif state == "dump":
        if not template_ids:
            module.fail_json(msg='Template not found: %s' % template_name)
        module.exit_json(changed=False, template_json=existing_template_json)

    elif state == "present":
        child_template_ids = None
        if link_templates is not None:
            child_template_ids = template.get_template_ids(link_templates)

        clear_template_ids = []
        if clear_templates is not None:
            clear_template_ids = template.get_template_ids(clear_templates)

        group_ids = None
        if template_groups is not None:
            # If the template exists, compare the already set groups
            existing_groups = None
            if existing_template_json:
                existing_groups = set(list(group['name'] for group in existing_template_json['zabbix_export']['groups']))
            if not existing_groups or set(template_groups) != existing_groups:
                group_ids = template.get_group_ids_by_group_names(template_groups)

        macros = None
        if template_macros is not None:
            existing_macros = None
            if existing_template_json:
                existing_macros = set(existing_template_json['zabbix_export']['templates'][0]['macros'])
            if not existing_macros or set(template_macros) != existing_macros:
                macros = template_macros

        if not template_ids:
            template.add_template(template_name, template_json, group_ids,
                                  child_template_ids, macros)
            module.exit_json(changed=True,
                             result="Successfully added template: %s" %
                             template_name)
        else:
            changed = template.update_template(template_ids[0], template_json,
                                               group_ids, child_template_ids,
                                               clear_template_ids, macros,
                                               existing_template_json)
            module.exit_json(changed=changed,
                             result="Successfully updateed template: %s" %
                             template_name)
Exemplo n.º 28
0
import csv
from zabbix_api import ZabbixAPI

URL = 'http://zabbix.fortalnet.net.br/zabbix/api_jsonrpc.php'
USERNAME = '******'
PASSWORD = ''

try:
	zapi = ZabbixAPI(URL, timeout=180)
	zapi.login(USERNAME, PASSWORD)
	print('Conectado na API do Zabbix, versao: {}'.format(zapi.api_version()))



except Exception as err:
	print('Falha ao Conectar na API no Zabbix')
	print('Erro: {}'.format(err))




def create_user(alias, grupoid):
	try:
		create_user = zapi.user.create({
			"alias": alias,
			"passwd": '132@mudar',
			"usrgrps": [
			{
				"usrgrpid": grupoid
			}
			]
Exemplo n.º 29
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################
# Autor: Janssen dos Reis Lima - [email protected]    #
# Objetivo: Fazer o ack no evento automaticamente             #
# Versao: 1.0                                                 #
###############################################################
from zabbix_api import ZabbixAPI
import sys, re

# Parametros de acesso da interface web do Zabbix
server = "http://localhost/zabbix"
username = "******"
password = "******"

zapi = ZabbixAPI(server=server)
zapi.login(username, password)

zapi.event.acknowledge({
    "eventids":
    sys.argv[1],
    "message":
    "Ticket " + str(sys.argv[2]) + " criado no OTRS."
})
Exemplo n.º 30
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            state=dict(type='str',
                       required=False,
                       default='present',
                       choices=['present', 'absent']),
            server_url=dict(type='str', required=True, aliases=['url']),
            host_names=dict(type='list',
                            required=False,
                            default=None,
                            aliases=['host_name']),
            minutes=dict(type='int', required=False, default=10),
            host_groups=dict(type='list',
                             required=False,
                             default=None,
                             aliases=['host_group']),
            login_user=dict(type='str', required=True),
            login_password=dict(type='str', required=True, no_log=True),
            validate_certs=dict(type='bool', required=False, default=True),
            http_login_user=dict(type='str', required=False, default=None),
            http_login_password=dict(type='str',
                                     required=False,
                                     default=None,
                                     no_log=True),
            name=dict(type='str', required=True),
            desc=dict(type='str', required=False,
                      default="Created by Ansible"),
            collect_data=dict(type='bool', required=False, default=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)

    host_names = module.params['host_names']
    host_groups = module.params['host_groups']
    state = module.params['state']
    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']
    minutes = module.params['minutes']
    name = module.params['name']
    desc = module.params['desc']
    server_url = module.params['server_url']
    collect_data = module.params['collect_data']
    timeout = module.params['timeout']

    if collect_data:
        maintenance_type = 0
    else:
        maintenance_type = 1

    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)
    # zabbix_api can call sys.exit() so we need to catch SystemExit here
    except (Exception, SystemExit) as e:
        module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)

    changed = False

    if state == "present":

        if not host_names and not host_groups:
            module.fail_json(
                msg=
                "At least one host_name or host_group must be defined for each created maintenance."
            )

        now = datetime.datetime.now().replace(second=0)
        start_time = time.mktime(now.timetuple())
        period = 60 * int(minutes)  # N * 60 seconds

        if host_groups:
            (rc, group_ids, error) = get_group_ids(zbx, host_groups)
            if rc != 0:
                module.fail_json(msg="Failed to get group_ids: %s" % error)
        else:
            group_ids = []

        if host_names:
            (rc, host_ids, error) = get_host_ids(zbx, host_names)
            if rc != 0:
                module.fail_json(msg="Failed to get host_ids: %s" % error)
        else:
            host_ids = []

        (rc, maintenance, error) = get_maintenance(zbx, name)
        if rc != 0:
            module.fail_json(
                msg="Failed to check maintenance %s existence: %s" %
                (name, error))

        if maintenance and (
                sorted(group_ids) != sorted(maintenance["groupids"])
                or sorted(host_ids) != sorted(maintenance["hostids"])
                or str(maintenance_type) != maintenance["maintenance_type"]
                or str(int(start_time)) != maintenance["active_since"] or
                str(int(start_time + period)) != maintenance["active_till"]):
            if module.check_mode:
                changed = True
            else:
                (rc, data,
                 error) = update_maintenance(zbx, maintenance["maintenanceid"],
                                             group_ids, host_ids, start_time,
                                             maintenance_type, period, desc)
                if rc == 0:
                    changed = True
                else:
                    module.fail_json(msg="Failed to update maintenance: %s" %
                                     error)

        if not maintenance:
            if module.check_mode:
                changed = True
            else:
                (rc, data, error) = create_maintenance(zbx, group_ids,
                                                       host_ids, start_time,
                                                       maintenance_type,
                                                       period, name, desc)
                if rc == 0:
                    changed = True
                else:
                    module.fail_json(msg="Failed to create maintenance: %s" %
                                     error)

    if state == "absent":

        (rc, maintenance, error) = get_maintenance(zbx, name)
        if rc != 0:
            module.fail_json(
                msg="Failed to check maintenance %s existence: %s" %
                (name, error))

        if maintenance:
            if module.check_mode:
                changed = True
            else:
                (rc, data,
                 error) = delete_maintenance(zbx, maintenance["maintenanceid"])
                if rc == 0:
                    changed = True
                else:
                    module.fail_json(msg="Failed to remove maintenance: %s" %
                                     error)

    module.exit_json(changed=changed)