Beispiel #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"
Beispiel #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),
        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)
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))
Beispiel #4
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')
Beispiel #5
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")
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))
Beispiel #7
0
class ZapiWrapper(object):
    """
    A simple wrapper over the Zabbix API
    """
    def __init__(self, module, zbx=None):
        self._module = module

        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)

        # check if zbx is already instantiated or not
        if zbx is not None and isinstance(zbx, ZabbixAPI):
            self._zapi = zbx
        else:
            server_url = module.params['server_url']
            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']
            self._zapi = ZabbixAPI(server_url,
                                   timeout=timeout,
                                   user=http_login_user,
                                   passwd=http_login_password,
                                   validate_certs=validate_certs)

        self.login()

        self._zbx_api_version = self._zapi.api_version()[:5]

    def login(self):
        # check if api already logged in
        if not self._zapi.auth != '':
            try:
                login_user = self._module.params['login_user']
                login_password = self._module.params['login_password']
                self._zapi.login(login_user, login_password)
                atexit.register(self._zapi.logout)
            except Exception as e:
                self._module.fail_json(
                    msg="Failed to connect to Zabbix server: %s" % e)
Beispiel #8
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
Beispiel #9
0
import time
import json
import math


#zsvr = str(input('Insira o server: '))
zsvr = "https://www.tjms.jus.br/zabbix"
username = str(input('Insira o usuario: '))
password = str(getpass.getpass('Insira a senha: '))

#instanciando a API
conexao = ZabbixAPI(server = zsvr)
conexao.login(username, password)

#lendo versao
versao = conexao.api_version()
print ("Versão do Zabbix Server: ", versao)




hostgroup = conexao.hostgroup.get({"output": "extend", "sortfield": "name"})
for x in hostgroup: #vendo os grupos de host
    print (x['groupid'], "-", x['name'])




y = int(input('Insira o GroupID: '))

Beispiel #10
0
##########################################
#  Busca informação da versão do Zabbix
##########################################

#importando o zabbixapi
from zabbix_api import ZabbixAPI
import config

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

print("Versão da API: ", zapi.api_version())
Beispiel #11
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)
@author: Janssen dos Reis Lima
"""
from zabbix_api import ZabbixAPI

zabbix_server = "http://127.0.0.1:1080"  #Endereço ou IP ou FQDN do servidor do Zabbix.
username = "******"  #Informe usuario para acessar. Usuario com perfil de administrador do Zabbix, não necessariamente o 'admin' padrao.
password = "******"  #Senha

#Instanciando a API
#conexao = ZabbixAPI(server = zabbix_server, log_level=6)
conexao = ZabbixAPI(server=zabbix_server)
conexao.login(username, password)

# verificar versao zabbix
versao = conexao.api_version()
print "Versão do Zabbix Server: ", versao

# Exibir hosts cadastrados
hosts = conexao.host.get({"output": "extend", "sortfield": "name"})
for x in hosts:
    print x['available'], "-", x['hostid'], "-", x['name']

#Cadastrar hosts
#conexao.host.create({"host": "Centos",
#                 "interfaces": [ {"type": "1",
#                 "main": "1",
#                 "useip": "1",
#                 "ip": "19.168.0.1",
#                 "dns": "",
#                 "port": "10052"}],
Beispiel #13
0
data = zg.get("vm.discovery[*]")
try:
  result = json.loads(data)
#  result = json.dumps(result, indent=4)
except:
  print "Cannot decode VMBIX response"
  logging.error("Cannot decode VMBIX response")
  exit(1)
result = result["data"]

# Connection to Zabbix API
zapi = ZabbixAPI(server = ZBXURL, path = "")
zapi.login(ZBXUSER, ZBXPASSWORD)

# Get Zabbix data
if zapi.api_version() <= 1.4:
  logging.error('Example script works only with API 1.4 or higher.')
  exit(1)
hosts = zapi.host.get({"output": "extend", "selectGroups": ["name"], "selectParentTemplates": ["name"]})

try:
  get = zapi.hostgroup.get({
    "output": "extend",
    "filter": {
        "name": VMGROUP
    }
  })
  groupids = [{"groupid": x['groupid']} for x in get]
  logging.info("Groups : %s" %(groupids))
  #groupid = get[0]['groupid']
except:
Beispiel #14
0
    p.print_help()
    print "NOTE: Zabbix 1.8.0 doesn't check LDAP when authenticating."
    sys.exit(-1)

def errmsg(msg):
    sys.stderr.write(msg + "\n")
    sys.exit(-1)

if  __name__ == "__main__":
    options, args = get_options()

    zapi = ZabbixAPI(server=options.server,log_level=3)

    try:
        zapi.login(options.username, options.password)
        print "Zabbix API Version: %s" % zapi.api_version()
        print "Logged in: %s" % str(zapi.test_login())
    except ZabbixAPIException, e:
        sys.stderr.write(str(e) + '\n')

    try:
        for host in zapi.host.get({ 'monitored_hosts' : True,'extendoutput' : True}):
            if host['dns'] == "":
                print "%s - %s - %s" % (host['host'], host['ip'], host['useip'])
            else:
                print "%s - %s - %s" % (host['dns'], host['ip'], host['useip'])

            if host['useip'] == "1" and host['dns'] != "":
                print "Updating %s to monitor by FQDN." % host['dns']
                newhost = host
                newhost['useip'] = 0
Beispiel #15
0
    sys.exit(-1)


def errmsg(msg):
    sys.stderr.write(msg + "\n")
    sys.exit(-1)


if __name__ == "__main__":
    options, args = get_options()

    zapi = ZabbixAPI(server=options.server, log_level=3)

    try:
        zapi.login(options.username, options.password)
        print "Zabbix API Version: %s" % zapi.api_version()
        print "Logged in: %s" % str(zapi.test_login())
    except ZabbixAPIException, e:
        sys.stderr.write(str(e) + '\n')

    try:
        for host in zapi.host.get({
                'monitored_hosts': True,
                'extendoutput': True
        }):
            if host['dns'] == "":
                print "%s - %s - %s" % (host['host'], host['ip'],
                                        host['useip'])
            else:
                print "%s - %s - %s" % (host['dns'], host['ip'], host['useip'])
Beispiel #16
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), timeout=dict(type='int', default=10),
        name=dict(type='str', required=True),
        description=dict(type='str', required=False, default=''),
        state=dict(type='str', default='present', choices=['present', 'absent']),
        type=dict(type='str', choices=['email', 'script', 'sms', 'webhook', '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']),
        # Webhook
        webhook_script=dict(type='str'),
        webhook_timeout=dict(type='str', default='30s'),
        process_tags=dict(type='bool', default=False),
        event_menu=dict(type='bool', default=False),
        event_menu_url=dict(type='str'),
        event_menu_name=dict(type='str'),
        webhook_params=dict(
            type='list',
            elements='dict',
            default=[],
            required=False,
            options=dict(
                name=dict(type='str', required=True),
                value=dict(type='str', default='')
            )
        ),
        message_templates=dict(
            type='list',
            elements='dict',
            default=[],
            required=False,
            options=dict(
                eventsource=dict(type='str', choices=['triggers', 'discovery', 'autoregistration', 'internal']),
                recovery=dict(type='str', choices=['operations', 'recovery_operations', 'update_operations']),
                subject=dict(type='str', default=''),
                body=dict(type='str', default='')
            ),
            required_together=[
                ['eventsource', 'recovery']
            ],
        )
    )

    # this is used to simulate `required_if` of `AnsibleModule`, but only when state=present
    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']],
        ['type', 'webhook', ['webhook_script']],
        ['event_menu', True, ['event_menu_url', 'event_menu_name']],
        ['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']
    description = module.params['description']
    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']
    # Webhook
    webhook_script = module.params['webhook_script']
    webhook_timeout = module.params['webhook_timeout']
    process_tags = module.params['process_tags']
    event_menu = module.params['event_menu']
    event_menu_url = module.params['event_menu_url']
    event_menu_name = module.params['event_menu_name']
    webhook_params = module.params['webhook_params']
    # Message template
    message_templates = module.params['message_templates']

    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)

    zbx_api_version = zbx.api_version()[:3]
    mediatype_exists, mediatype_id = check_if_mediatype_exists(module, zbx, name, zbx_api_version)

    parameters = construct_parameters(
        name=name,
        description=description,
        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,
        webhook_script=webhook_script,
        webhook_timeout=webhook_timeout,
        process_tags=process_tags,
        event_menu=event_menu,
        event_menu_url=event_menu_url,
        event_menu_name=event_menu_name,
        webhook_params=webhook_params,
        message_templates=message_templates,
        zbx_api_version=zbx_api_version
    )

    if 'unsupported_parameter' in parameters:
        module.fail_json(msg="%s is unsupported for Zabbix version %s" % (parameters['unsupported_parameter'], parameters['zbx_api_version']))

    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
                )
            )
Beispiel #17
0
        logger.error('Configuration file {} not found'.format(server_config))
        sys.exit()

    try:
        zabbix_server = configuration['zabbix_server']
        zabbix_login = configuration['zabbix_login']
        zabbix_password = configuration['zabbix_password']
        redis_host = configuration['redis_host']
        redis_port = configuration['redis_port']
    except KeyError as e:
        logger.error('Not found in config: {}'.format(e))
        sys.exit()

    zapi = ZabbixAPI(zabbix_server)
    zapi.login(zabbix_login, zabbix_password)
    logger.info('Connected to Zabbix API Version {}'.format(zapi.api_version()))

    killer = GracefulKiller()

    r = redis.Redis(host=redis_host, port=redis_port, db=0)
    p = r.pubsub(ignore_subscribe_messages=True)
    p.subscribe(**{'notify-channel': Redis_handler})
    logger.info(p.get_message())

    while True:
        if killer.receivedSignal:
            if killer.receivedTermSignal:
                logging.warning("Gracefully exiting due to receipt of signal {}".format(killer.lastSignal))
                sys.exit()
            else:
                logging.warning("Ignoring signal {}".format(killer.lastSignal))
Beispiel #18
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', 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),
            host_groups=dict(type='list', required=False),
            link_templates=dict(type='list', required=False),
            status=dict(type='str', default="enabled", choices=['enabled', 'disabled']),
            state=dict(type='str', default="present", choices=['present', 'absent']),
            inventory_mode=dict(type='str', required=False, choices=['automatic', 'manual', 'disabled']),
            ipmi_authtype=dict(type='int', default=None),
            ipmi_privilege=dict(type='int', default=None),
            ipmi_username=dict(type='str', required=False, default=None),
            ipmi_password=dict(type='str', required=False, default=None, no_log=True),
            tls_connect=dict(type='int', default=1),
            tls_accept=dict(type='int', default=1),
            tls_psk_identity=dict(type='str', required=False),
            tls_psk=dict(type='str', required=False),
            ca_cert=dict(type='str', required=False, aliases=['tls_issuer']),
            tls_subject=dict(type='str', required=False),
            inventory_zabbix=dict(type='dict', required=False),
            timeout=dict(type='int', default=10),
            interfaces=dict(type='list', required=False),
            force=dict(type='bool', default=True),
            proxy=dict(type='str', required=False),
            visible_name=dict(type='str', required=False),
            description=dict(type='str', required=False),
            macros=dict(
                type='list',
                elements='dict',
                aliases=['user_macros'],
                options=dict(
                    macro=dict(type='str', required=True),
                    value=dict(type='str', required=True),
                    description=dict(type='str', required=False, default='')
                )
            ),
            tags=dict(
                type='list',
                elements='dict',
                aliases=['host_tags'],
                options=dict(
                    tag=dict(type='str', required=True),
                    value=dict(type='str', 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']
    host_name = module.params['host_name']
    visible_name = module.params['visible_name']
    description = module.params['description']
    host_groups = module.params['host_groups']
    link_templates = module.params['link_templates']
    inventory_mode = module.params['inventory_mode']
    ipmi_authtype = module.params['ipmi_authtype']
    ipmi_privilege = module.params['ipmi_privilege']
    ipmi_username = module.params['ipmi_username']
    ipmi_password = module.params['ipmi_password']
    tls_connect = module.params['tls_connect']
    tls_accept = module.params['tls_accept']
    tls_psk_identity = module.params['tls_psk_identity']
    tls_psk = module.params['tls_psk']
    tls_issuer = module.params['ca_cert']
    tls_subject = module.params['tls_subject']
    inventory_zabbix = module.params['inventory_zabbix']
    status = module.params['status']
    state = module.params['state']
    timeout = module.params['timeout']
    interfaces = module.params['interfaces']
    force = module.params['force']
    proxy = module.params['proxy']
    macros = module.params['macros']
    tags = module.params['tags']

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

    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)

    template_ids = []
    if link_templates:
        template_ids = host.get_template_ids(link_templates)

    group_ids = []

    if host_groups:
        group_ids = host.get_group_ids_by_group_names(host_groups)

    ip = ""
    if interfaces:
        # ensure interfaces are well-formed
        for interface in interfaces:
            if 'type' not in interface:
                module.fail_json(msg="(interface) type needs to be specified for interface '%s'." % interface)
            interfacetypes = {'agent': 1, 'snmp': 2, 'ipmi': 3, 'jmx': 4}
            if interface['type'] in interfacetypes.keys():
                interface['type'] = interfacetypes[interface['type']]
            if interface['type'] < 1 or interface['type'] > 4:
                module.fail_json(msg="Interface type can only be 1-4 for interface '%s'." % interface)
            if 'useip' not in interface:
                interface['useip'] = 0
            if 'dns' not in interface:
                if interface['useip'] == 0:
                    module.fail_json(msg="dns needs to be set if useip is 0 on interface '%s'." % interface)
                interface['dns'] = ''
            if 'ip' not in interface:
                if interface['useip'] == 1:
                    module.fail_json(msg="ip needs to be set if useip is 1 on interface '%s'." % interface)
                interface['ip'] = ''
            if 'main' not in interface:
                interface['main'] = 0
            if 'port' in interface and not isinstance(interface['port'], str):
                try:
                    interface['port'] = str(interface['port'])
                except ValueError:
                    module.fail_json(msg="port should be convertable to string on interface '%s'." % interface)
            if 'port' not in interface:
                if interface['type'] == 1:
                    interface['port'] = "10050"
                elif interface['type'] == 2:
                    interface['port'] = "161"
                elif interface['type'] == 3:
                    interface['port'] = "623"
                elif interface['type'] == 4:
                    interface['port'] = "12345"

            if interface['type'] == 1:
                ip = interface['ip']

    if macros:
        # convert macros to zabbix native format - {$MACRO}
        for macro in macros:
            macro['macro'] = macro['macro'].upper()
            if not macro['macro'].startswith('{$'):
                macro['macro'] = '{$' + macro['macro']
            if not macro['macro'].endswith('}'):
                macro['macro'] = macro['macro'] + '}'
            if LooseVersion(zbx.api_version()[:5]) <= LooseVersion('4.4.0'):
                if 'description' in macro:
                    macro.pop('description', False)

    # Use proxy specified, or set to 0
    if proxy:
        proxy_id = host.get_proxyid_by_proxy_name(proxy)
    else:
        proxy_id = 0

    # check if host exist
    is_host_exist = host.is_host_exist(host_name)

    if is_host_exist:
        # get host id by host name
        zabbix_host_obj = host.get_host_by_host_name(host_name)
        host_id = zabbix_host_obj['hostid']

        # If proxy is not specified as a module parameter, use the existing setting
        if proxy is None:
            proxy_id = int(zabbix_host_obj['proxy_hostid'])

        if state == "absent":
            # remove host
            host.delete_host(host_id, host_name)
            module.exit_json(changed=True, result="Successfully delete host %s" % host_name)
        else:
            if not host_groups:
                # if host_groups have not been specified when updating an existing host, just
                # get the group_ids from the existing host without updating them.
                group_ids = host.get_group_ids_by_host_id(host_id)

            # get existing host's interfaces
            exist_interfaces = host._zapi.hostinterface.get({'output': 'extend', 'hostids': host_id})

            # if no interfaces were specified with the module, start with an empty list
            if not interfaces:
                interfaces = []

            # When force=no is specified, append existing interfaces to interfaces to update. When
            # no interfaces have been specified, copy existing interfaces as specified from the API.
            # Do the same with templates and host groups.
            if not force or not interfaces:
                for interface in copy.deepcopy(exist_interfaces):
                    # remove values not used during hostinterface.add/update calls
                    for key in tuple(interface.keys()):
                        if key in ['interfaceid', 'hostid', 'bulk']:
                            interface.pop(key, None)

                    for index in interface.keys():
                        if index in ['useip', 'main', 'type']:
                            interface[index] = int(interface[index])

                    if interface not in interfaces:
                        interfaces.append(interface)

            if not force or link_templates is None:
                template_ids = list(set(template_ids + host.get_host_templates_by_host_id(host_id)))

            if not force:
                for group_id in host.get_group_ids_by_host_id(host_id):
                    if group_id not in group_ids:
                        group_ids.append(group_id)

                # Macros not present in host.update will be removed if we dont copy them when force=no
                if macros is not None and 'macros' in zabbix_host_obj.keys():
                    provided_macros = [m['macro'] for m in macros]
                    existing_macros = zabbix_host_obj['macros']
                    for macro in existing_macros:
                        if macro['macro'] not in provided_macros:
                            macros.append(macro)

                # Tags not present in host.update will be removed if we dont copy them when force=no
                if tags is not None and 'tags' in zabbix_host_obj.keys():
                    provided_tags = [t['tag'] for t in tags]
                    existing_tags = zabbix_host_obj['tags']
                    for tag in existing_tags:
                        if tag['tag'] not in provided_tags:
                            tags.append(tag)

            # update host
            if host.check_all_properties(
                    host_id, group_ids, status, interfaces, template_ids, exist_interfaces, zabbix_host_obj, proxy_id,
                    visible_name, description, host_name, inventory_mode, inventory_zabbix, tls_accept,
                    tls_psk_identity, tls_psk, tls_issuer, tls_subject, tls_connect, ipmi_authtype, ipmi_privilege,
                    ipmi_username, ipmi_password, macros, tags):

                host.update_host(
                    host_name, group_ids, status, host_id, interfaces, exist_interfaces, proxy_id, visible_name,
                    description, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject,
                    ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password, macros, tags)

                host.link_or_clear_template(
                    host_id, template_ids, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer,
                    tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password)

                host.update_inventory_mode(host_id, inventory_mode)
                host.update_inventory_zabbix(host_id, inventory_zabbix)

                module.exit_json(changed=True,
                                 result="Successfully update host %s (%s) and linked with template '%s'"
                                        % (host_name, ip, link_templates))
            else:
                module.exit_json(changed=False)

    else:
        if state == "absent":
            # the host is already deleted.
            module.exit_json(changed=False)

        if not group_ids:
            module.fail_json(msg="Specify at least one group for creating host '%s'." % host_name)

        if not interfaces or (interfaces and len(interfaces) == 0):
            module.fail_json(msg="Specify at least one interface for creating host '%s'." % host_name)

        # create host
        host_id = host.add_host(
            host_name, group_ids, status, interfaces, proxy_id, visible_name, description, tls_connect, tls_accept,
            tls_psk_identity, tls_psk, tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username,
            ipmi_password, macros, tags)

        host.link_or_clear_template(
            host_id, template_ids, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject,
            ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password)

        host.update_inventory_mode(host_id, inventory_mode)
        host.update_inventory_zabbix(host_id, inventory_zabbix)

        module.exit_json(changed=True, result="Successfully added host %s (%s) and linked with template '%s'" % (
            host_name, ip, link_templates))
Beispiel #19
0
    import atexit
    atexit.register(cleanup)

    #get screens
    for screen in zapi.screen.get({
            "output": "extend",
            "selectScreenItems": "extend"
    }):
        print json.dumps(screen, indent=4)
    sys.exit(1)


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()
Beispiel #20
0
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))

hostgroups = zapi.hostgroup.get({"output": ['name'], "monitored_hotst": 1})

for hostgroup in hostgroups:
    hostgroup_id = hostgroup['groupid']
    hostgroup_name = hostgroup['name']
    print('{} - {} '.format(hostgroup_id, hostgroup_name))
Beispiel #21
0
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):

    NAME = 'community.zabbix.zabbix_inventory'

    def login_zabbix(self):
        # set proxy information if required
        proxy = self.get_option('proxy')
        os.environ['http_proxy'] = proxy
        os.environ['HTTP_PROXY'] = proxy
        os.environ['https_proxy'] = proxy
        os.environ['HTTPS_PROXY'] = proxy

        server_url = self.get_option('server_url')
        http_login_user = self.get_option('login_user')
        http_login_password = self.get_option('login_password')
        validate_certs = self.get_option('validate_certs')
        timeout = self.get_option('timeout')
        self._zapi = ZabbixAPI(server_url,
                               timeout=timeout,
                               user=http_login_user,
                               passwd=http_login_password,
                               validate_certs=validate_certs)
        self.login()
        self._zbx_api_version = self._zapi.api_version()[:5]

    def login(self):
        # check if api already logged in
        if not self._zapi.auth != '':
            try:
                login_user = self.get_option('login_user')
                login_password = self.get_option('login_password')
                self._zapi.login(login_user, login_password)
                atexit.register(self._zapi.logout)
            except Exception as e:
                self.display.vvv(msg="Failed to connect to Zabbix server: %s" %
                                 e)

    def verify_file(self, path):
        valid = False
        if super(InventoryModule, self).verify_file(path):
            if path.endswith(
                ('zabbix_inventory.yaml', 'zabbix_inventory.yml')):
                valid = True
            else:
                self.display.vvv(
                    'Skipping due to inventory source not ending in "zabbix_inventory.yaml" nor "zabbix_inventory.yml"'
                )
        return valid

    def parse(self,
              inventory,
              loader,
              path,
              cache=True):  # Plugin interface (2)
        super(InventoryModule, self).parse(inventory, loader, path)

        self._read_config_data(path)
        self.cache_key = self.get_cache_key(path)

        self.use_cache = self.get_option('cache') and cache
        self.update_cache = self.get_option('cache') and not cache

        self.login_zabbix()
        zapi_query = self.get_option('host_zapi_query')
        content = self._zapi.host.get(zapi_query)

        strict = self.get_option('strict')

        for record in content:
            # add host to inventory
            host_name = self.inventory.add_host(record['host'])
            # set variables for host
            for k in record.keys():
                self.inventory.set_variable(host_name, 'zbx_%s' % k, record[k])

            # added for compose vars and keyed groups
            self._set_composite_vars(
                self.get_option('compose'),
                self.inventory.get_host(host_name).get_vars(), host_name,
                strict)

            self._add_host_to_composed_groups(self.get_option('groups'),
                                              dict(), host_name, strict)
            self._add_host_to_keyed_groups(self.get_option('keyed_groups'),
                                           dict(), host_name, strict)

        # organize inventory by zabbix groups
        if self.get_option('add_zabbix_groups'):
            content = self._zapi.host.get({'selectGroups': ['name']})
            for record in content:
                host_name = record['host']
                if len(record['groups']) >= 1:
                    for group in record['groups']:
                        group_name = to_safe_group_name(group['name'])
                        self.inventory.add_group(group_name)
                        self.inventory.add_child(group_name, host_name)
			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()
Beispiel #23
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),
        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)

    zbx_api_version = zbx.api_version()[:3]
    mediatype_exists, mediatype_id = check_if_mediatype_exists(
        module, zbx, name, zbx_api_version)

    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,
                                      zbx_api_version=zbx_api_version)

    if 'unsupported_parameter' in parameters:
        module.fail_json(msg="%s is unsupported for Zabbix version %s" %
                         (parameters['unsupported_parameter'],
                          parameters['zbx_api_version']))

    if LooseVersion(zbx_api_version) >= LooseVersion('4.4'):
        # description key changed to name key from zabbix 4.4
        parameters['name'] = parameters.pop('description')

    if LooseVersion(zbx_api_version) <= LooseVersion('3.2'):
        # remove settings not supported till 3.4
        for key in ['maxsessions', 'maxattempts', 'attempt_interval']:
            del parameters[key]

    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))