Example #1
0
def maintenance_create(host_ip, start_time, end_time):
    ips = host_ip.split(',')
    acc_hostid = []
    err_ips = []
    for ip in ips:
        _host = host.is_monitor(ip)
        # print(_host)
        result_data['api'] = "根据ip新增对应监控主机的维护计划"
        if _host['status']:
            if _host['result']['status'] == '0':
                status = _host['result']['maintenance_status']
                if status == '0':
                    acc_hostid.append(_host['result']['hostid'])
                else:
                    err_ips.append(ip)
            else:
                err_ips.append(ip)
        else:
            err_ips.append(ip)
    if acc_hostid:
        maintenance_name = "%s_%s" % (''.join(
            str(n) for n in acc_hostid), str(start_time))
        maintenancecreate_json = {
            "method": "maintenance.create",
            "params": {
                "name":
                maintenance_name,
                "active_since":
                start_time,
                "active_till":
                end_time,
                "maintenance_type":
                0,
                "hostids":
                acc_hostid,
                "timeperiods": [{
                    "timeperiod_type": 0,
                    "start_date": start_time,
                    "period": end_time - start_time
                }]
            }
        }
        maintenance = Zabbix(maintenancecreate_json).api_post()
        if maintenance:
            # print("根据ip(%s)新增的维护ID是[%s]!" % (host_ip, maintenance['maintenanceids'][0]))
            if err_ips:
                maintenance[
                    'info'] = "请到zabbix上检查这些ip(%s)对应监控的状态是否正常,没有添加到维护计划当中!" % ','.join(
                        str(n) for n in err_ips)
                maintenance['err_ips'] = err_ips
            maintenance['maintenance_name'] = maintenance_name
            result_data['result'] = maintenance
            result_data['status'] = True
        else:
            result_data['result'] = '创建维护计划失败!'
            result_data['status'] = False
    else:
        result_data['result'] = '选择的ip对应的监控状态都不正常,创建维护计划失败!'
        result_data['status'] = False
    return result_data
Example #2
0
def hoststatus_update(host_ip, status):
    _host = is_monitor(host_ip)
    # print(_host)
    result_data['api'] = "根据ip修改对应监控主机的监控状态"
    if _host['status']:
        _status = _host['result']['status']
        if _status != status:
            hostdelect_json = {
                "method": "host.update",
                "params": {
                    "hostid": _host['result']['hostid'],
                    "status": status
                }
            }
            host = Zabbix(hostdelect_json).api_post()
            if host:
                result_data['result'] = "已将ip(%s)对应监控主机的状态更改为(%s)!" % (host_ip,
                                                                       status)
                result_data['status'] = True
            else:
                result_data['result'] = '根据ip(%s)修改对应主机的监控状态失败!' % host_ip
                result_data['status'] = False
        else:
            result_data['result'] = '根据ip(%s)查询到对应主机状态和要修改的状态值一致!' % host_ip
            result_data['status'] = False
    else:
        result_data['result'] = _host['result']
        result_data['status'] = False
    return result_data
Example #3
0
def host_delete(host_ip):
    _host = is_monitor(host_ip)
    # print(_host)
    result_data['api'] = "根据ip删除对应的监控"
    if _host['status']:
        status = _host['result']['status']
        if int(status) == 1:
            hostdelect_json = {
                "method": "host.delete",
                "params": [_host['result']['hostid']]
            }
            host = Zabbix(hostdelect_json).api_post()
            if host:
                # print("根据ip(%s)已删除该监控!" % host_ip)
                result_data['result'] = "根据ip(%s)已删除该监控!" % host_ip
                result_data['status'] = True
            else:
                result_data['result'] = "根据ip(%s)删除对应的监控失败!" % host_ip
                result_data['status'] = False
        else:
            # print("根据ip(%s),查询到对应主机agent还在运行,不能删除监控项,请关闭agent并将监控主机状态设置为停用后再删除监控项!" % host_ip)
            result_data['result'] = "根据ip(%s)查询到对应主机状态为启用,不能删除监控项!" % host_ip
            result_data['status'] = False
    else:
        result_data['result'] = _host['result']
        result_data['status'] = False
    return result_data
Example #4
0
    def Add(self, request):
        api_obs = u"Inclusao de grupo de usuarios no Zabbix"
        api_log_referencia_id = None
        api_log_action_nome = "criar"
        api_log_tipo_nome = "zab"
        alog = Log.saveAlog(request)

        #buscando id do servidor
        try:
            servidor = Servidor.objects.get(nome=local.SERVER_ZABBIX_DEFAULT)
        except ObjectDoesNotExist:
            return raiseError(alog, "server_not_exist", request, None, api_obs,
                              api_log_referencia_id, api_log_action_nome,
                              api_log_tipo_nome)
        else:
            self.usuario_servidor = servidor.id

        # valores caso nao consiga incluir usuario no Zabbix
        error_transaction = None
        grupo_usuario_tentativa = 1
        status = Status.objects.get(label='INCLUIR')
        usrgrpids = 0

        # tentando incluir grupo de usuarios no Zabbix
        try:
            zab_usuario = local.SERVER_ZABBIX[servidor.nome]['usuario']
            zab_senha = local.SERVER_ZABBIX[servidor.nome]['senha']
            zab = Zabbix()
            zab.setHost(servidor.endereco)
            zab.setUser(zab_usuario)
            zab.setPassword(zab_senha)
            if zab.login() == True:
                create_resp = zab.createUserGroup(self.grupousuario_nome)
                if create_resp:
                    jresp = json.loads(create_resp)
                    usrgrpids = int(jresp['result']['usrgrpids'][0])
        except:
            retorno = {"Success": False, "Error": "ZabbixError"}
            return retorno

        #retornando da inclusao
        retorno = {
            "Success": True,
            "UserGroupIds": usrgrpids,
            "Nome": self.grupousuario_nome
        }
        return retorno
Example #5
0
    def Add(self, request):
        api_obs = u"Inclusao de action no Zabbix"
        api_log_referencia_id = None
        api_log_action_nome = "criar"
        api_log_tipo_nome = "zab"
        alog = Log.saveAlog(request)

        #buscando id do servidor
        try:
            servidor   = Servidor.objects.get(nome=local.SERVER_ZABBIX_DEFAULT)
        except  ObjectDoesNotExist:
            return raiseError(alog,"server_not_exist",request,None,api_obs,api_log_referencia_id,api_log_action_nome,api_log_tipo_nome) 
        else:
            self.usuario_servidor = servidor.id

        #buscando id do host
        try:
            host    = Host.objects.get(nome=self.nome)
        except  ObjectDoesNotExist:
            return raiseError(alog,"host_not_exist",request,None,api_obs,api_log_referencia_id,api_log_action_nome,api_log_tipo_nome) 
        else:
            host_id  = host.id

        # valores caso nao consiga incluir action no Zabbix
        error_transaction = None
        self.tentativa = 1
        status   = Status.objects.get(label='INCLUIR')
        actionids = 0

        # tentando incluir action no Zabbix
        try:
            zab_usuario    = local.SERVER_ZABBIX[servidor.nome]['usuario']
            zab_senha       = local.SERVER_ZABBIX[servidor.nome]['senha']
            zab = Zabbix()
            zab.setHost(servidor.endereco)
            zab.setUser(zab_usuario)
            zab.setPassword(zab_senha)
            if zab.login() == True:
                create_resp = zab.createPingAction( self.nome, int(self.user_group_id), int(self.host_group_id))
                if  create_resp:
                    jresp = json.loads(create_resp)
                    actionids = int(jresp['result']['actionids'][0])
                    status   = Status.objects.get(label='ATIVO')
                    self.tentativa = 0
        except Exception, error:
            return False
Example #6
0
    def incluirUsuario():
        api_obs = u"Incluir Usuario"
        api_log_referencia_id = None
        api_log_action_nome = "add"
        api_log_tipo_nome = "script"
        alog = "script"

        usuario = Usuario.objects.filter(status__label='incluir')
        status = Status.objects.get(label='ativo')
        if status:
            usuario_status = status.id

        for aUsuario in usuario:
            servidor = aUsuario.servidor.nome
            email = aUsuario.email
            senha = aUsuario.senha
            userids = 0
            zab_endereco = aUsuario.servidor.endereco
            zab_usuario = local.SERVER_ZABBIX[servidor]['usuario']
            zab_senha = local.SERVER_ZABBIX[servidor]['senha']
            zab = Zabbix()
            zab.setHost(zab_endereco)
            zab.setUser(zab_usuario)
            zab.setPassword(zab_senha)
            if zab.login() == True:
                create_resp = zab.createUser(email, senha,
                                             local.ZABBIX_USRGRPID)
                if create_resp:
                    jresp = json.loads(create_resp)
                    userids = int(jresp['result']['userids'][0])

            with transaction.commit_manually():
                try:
                    if userids != 0:
                        print '1'
                        usuario.status = usuario_status
                        usuario.zabbix_id = userids
                    else:
                        print '0'
                        usuario.tentativa = usuario.tentativa + 1
                    usuario.save()
                except:
                    pass

        return True
Example #7
0
    def Add(self, request):
        api_obs = u"Inclusao de grupo de hosts no Zabbix"
        api_log_referencia_id = None
        api_log_action_nome = "criar"
        api_log_tipo_nome = "zab"
        alog = Log.saveAlog(request)

        #buscando id do servidor
        try:
            servidor = Servidor.objects.get(nome=self.grupohost_servidor)
        except ObjectDoesNotExist:
            return raiseError(alog, "server_not_exist", request, None, api_obs,
                              api_log_referencia_id, api_log_action_nome,
                              api_log_tipo_nome)
        else:
            servidor_id = servidor.id

        # valores caso nao consiga incluir host no Zabbix
        error_transaction = None
        grupo_host_tentativa = 1
        status = Status.objects.get(label='INCLUIR')
        hostgrpids = 0

        # tentando incluir grupo de hosts no Zabbix
        try:
            zab_usuario = local.SERVER_ZABBIX[servidor.nome]['usuario']
            zab_senha = local.SERVER_ZABBIX[servidor.nome]['senha']
            zab = Zabbix()
            zab.setHost(servidor.endereco)
            zab.setUser(zab_usuario)
            zab.setPassword(zab_senha)
            if zab.login() == True:
                create_resp = zab.createHostGroup(self.grupohost_nome)
                if create_resp:
                    jresp = json.loads(create_resp)
                    hostgrpids = int(jresp['result']['groupids'][0])
        except Exception, error:
            return str(error)
Example #8
0
def is_monitor(host_ip):
    result_data['api'] = "根据ip查询是否有对应的监控"
    hsotget_json = {
        "method": "host.get",
        "params": {
            "output": "extend",
            "search": {
                "ip": host_ip
            },
            "sortfield": "host"
        }
    }
    _host = Zabbix(hsotget_json).api_post()
    # print(_host)
    if _host:
        hsotinterfaceget_json = {
            "method": "hostinterface.get",
            "params": {
                "output": "extend",
                "hostids": _host[0]['hostid']
            }
        }
        host_interface = Zabbix(hsotinterfaceget_json).api_post()
        # print(host_interface)
        interface_ip = host_interface[0]['ip']
        if interface_ip == host_ip:
            # print("根据ip(%s)查询到有监控!" % host_ip)
            result_data['result'] = _host[0]
            result_data['status'] = True
        else:
            # print("根据ip(%s)没有找到监控!" % host_ip)
            result_data['result'] = "host_ip跟对应的agent_ip不一致!"
            result_data['status'] = False
    else:
        result_data['result'] = "根据ip(%s)没有找到监控!" % host_ip
        result_data['status'] = False
    return result_data
Example #9
0
def maintenance_delete(maintenanceid):
    result_data['api'] = "根据维护计划id删除维护计划"
    maintenanceid = maintenanceid.split(',')
    maintenancedelete_json = {
        "method": "maintenance.delete",
        "params": maintenanceid
    }
    maintenance = Zabbix(maintenancedelete_json).api_post()
    if maintenance:
        result_data['result'] = maintenance
        result_data['status'] = True
    else:
        result_data['result'] = '删除维护计划失败!'
        result_data['status'] = False
    return result_data
Example #10
0
def is_hostgroup(hostgroup_name):
    result_data['api'] = "根据名称查询是否有对应的主机群组"
    hostgroupget_json = {
        "method": "hostgroup.get",
        "params": {
            "output": "extend",
            "filter": {
                "name": [hostgroup_name]
            }
        }
    }
    _hostgroup = Zabbix(hostgroupget_json).api_post()
    if _hostgroup:
        # print("根据名称(%s)查询到有对应的主机群组!" % hostgroup_name)
        result_data['result'] = _hostgroup[0]
        result_data['status'] = True
    else:
        result_data['result'] = '根据名称(%s)没有查询到对应的主机群组!' % hostgroup_name
        result_data['status'] = False
    return result_data
Example #11
0
def hostname_update(host_ip, host_name):
    _host = is_monitor(host_ip)
    result_data['api'] = "根据ip修改对应监控主机的名称"
    if _host['status']:
        hostupdate_json = {
            "method": "host.update",
            "params": {
                "hostid": _host['result']['hostid'],
                "name": host_name
            }
        }
        host = Zabbix(hostupdate_json).api_post()
        if host:
            # print("已将ip(%s)对应监控主机的名称更改为(%s)!" % (host_ip, host_name))
            result_data['result'] = '已将ip(%s)对应监控主机的名称更改为(%s)!' % (host_ip,
                                                                   host_name)
            result_data['status'] = True
        else:
            result_data['result'] = '根据ip(%s)修改对应主机的名称失败!' % host_ip
            result_data['status'] = False
    else:
        result_data['result'] = _host['result']
        result_data['status'] = False
    return result_data
Example #12
0
def is_autoregistration(autoregistration_name):
    result_data['api'] = "根据名称查询对应的自动注册动作"
    autoregistration_json = {
        "method": "action.get",
        "params": {
            "output": "extend",
            "selectFilter": "extend",
            "filter": {
                "eventsource": 2,
                "name": autoregistration_name
            }
        }
    }
    autoregistration = Zabbix(autoregistration_json).api_post()
    if autoregistration:
        # print("根据名称(%s)查询到有自动注册的动作!" % autoregistration_name)
        result_data['result'] = autoregistration
        result_data['status'] = True
    else:
        # print("根据名称(%s)没有查询到有自动注册的动作!" % autoregistration_name)
        result_data[
            'result'] = "根据名称(%s)没有查询到有自动注册的动作!" % autoregistration_name
        result_data['status'] = False
    return result_data
Example #13
0
    def Add(self, request):
        api_obs = u"Inclusao de host no Zabbix"
        api_log_referencia_id = None
        api_log_action_nome = "criar"
        api_log_tipo_nome = "zab"
        alog = Log.saveAlog(request)

        #buscando id do servidor
        try:
            servidor   = Servidor.objects.get(nome=local.SERVER_ZABBIX_DEFAULT)
        except  ObjectDoesNotExist:
            return raiseError(alog,"server_not_exist",request,None,api_obs,api_log_referencia_id,api_log_action_nome,api_log_tipo_nome) 
        else:
            self.usuario_servidor = servidor.id

        usuario = Usuario.objects.filter(usuario=self.usuario)
        email   = Usuario.objects.filter(email=self.email)

        #incluindo host, buscando id do usuario
        try:
            usuario   = Usuario.objects.get(nome=self.nome)
        except  ObjectDoesNotExist:
            return raiseError(alog,"user_not_exist",request,None,api_obs,api_log_referencia_id,api_log_action_nome,api_log_tipo_nome) 
        else:
            host_usuario  = usuario.id
            usuario_servidor = usuario.servidor_id
            host_servidor_endereco = servidor.endereco
         
        #verificando porta e endereço iguais
        endereco    = Host.objects.filter(endereco=self.endereco)
        porta           = Host.objects.filter(porta=self.porta)
        if endereco and porta:
            return raiseError(alog,"host_same_address_port",request,None,api_obs,api_log_referencia_id,api_log_action_nome,api_log_tipo_nome)
        else:
            pass
       
        # valores caso nao consiga incluir no Zabbix
        error_transaction = None
        self.tentativa = 1
        status   = Status.objects.get(label='INCLUIR')
        hostids = 0

        # tentando incluir host no Zabbix
        try:
            zab_usuario    = local.SERVER_ZABBIX[servidor.nome]['usuario']
            zab_senha       = local.SERVER_ZABBIX[servidor.nome]['senha']
            zab = Zabbix()
            zab.setHost(servidor.endereco)
            zab.setUser(zab_usuario)
            zab.setPassword(zab_senha)

            if zab.login() == True:
                useip = 1
                dns = ''
                interfaces =   { 
                    "type":  1, 
                    "main":  1, 
                    "useip":  useip, 
                    "ip":  self.endereco, 
                    "dns":  dns, 
                    "port":  self.porta
                }
                groups = {
                    "groupid" :  self.grupo_id
                }
                create_resp = zab.createHost(self.nome, interfaces, groups)
                if create_resp :
                    jresp = json.loads(create_resp)
                    hostids = int(jresp['hostids'][0])
                    status   = Status.objects.get(label='ATIVO')
                    self.tentativa = 0
        except Exception, error:
            pass
Example #14
0
    def Add(self, request):
        api_obs = u"Inclusao de usuario no Zabbix"
        api_log_referencia_id = None
        api_log_action_nome = "criar"
        api_log_tipo_nome = "zab"
        alog = Log.saveAlog(request)

        #buscando id do servidor
        try:
            servidor   = Servidor.objects.get(nome=local.SERVER_ZABBIX_DEFAULT)
        except  ObjectDoesNotExist:
            return raiseError(alog,"server_not_exist",request,None,api_obs,api_log_referencia_id,api_log_action_nome,api_log_tipo_nome) 
        else:
            self.usuario_servidor = servidor.id
        usuario = Usuario.objects.filter(usuario=self.usuario_usuario)
        email   = Usuario.objects.filter(email=self.usuario_email)

        #verificando se usuario ou e-mail existem
        if usuario:
            return raiseError(alog,"user_exist",request,None,api_obs,api_log_referencia_id,api_log_action_nome,api_log_tipo_nome)
        elif email:
            return raiseError(alog,"email_exist",request,None,api_obs,api_log_referencia_id,api_log_action_nome,api_log_tipo_nome)
        error_transaction = None

        # valores caso nao consiga incluir usuario no Zabbix
        usuario_tentativa = 1
        status   = Status.objects.get(label='INCLUIR')
        userids = 0

        # tentando incluir usuario no Zabbix
        try:
            zab_usuario    = local.SERVER_ZABBIX[servidor.nome]['usuario']
            zab_senha       = local.SERVER_ZABBIX[servidor.nome]['senha']
            zab = Zabbix()
            zab.setHost(servidor.endereco)
            zab.setUser(zab_usuario)
            zab.setPassword(zab_senha)
            if zab.login() == True:
                create_resp = zab.createUser(self.usuario_nome, self.usuario_senha, self.usuario_grupo_id)
                if create_resp :
                    jresp = json.loads(create_resp)
                    userids = int(jresp['result']['userids'][0])
                    status   = Status.objects.get(label='ATIVO')
                    zab.createMedia(userids, self.usuario_email)
                    usuario_tentativa = 0
        except:
            pass

        #incluindo usuario no mysql
        with transaction.commit_manually():
            try:
                usuario = Usuario(
                    nome=self.usuario_nome,
                    usuario=self.usuario_usuario,
                    label=self.usuario_label,
                    servidor =servidor,
                    email=self.usuario_email,
                    zabbix_id=userids,
                    zabbix_grupo_id=self.usuario_grupo_id,
                    contrato=self.usuario_contrato,
                    tentativa=usuario_tentativa,
                    status =status, 
                    data_criacao=datetime.datetime.now())
                usuario.save()
            except Exception,error:
                error_transaction = error
                transaction.rollback()
            else:
Example #15
0
#!/usr/bin/env python
import os
import sys, traceback, json
import logging, logging.handlers
from daemon import runner
import time
import datetime
import requests

homeDir = os.getenv("HOME")
project_path = os.path.join(homeDir, 'azabbix/azabbix')
sys.path.append(project_path)

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from api.models import *
from api.zabbix import Zabbix
import local

zab = Zabbix()
zab.setHost("https://localhost/zabbix")
zab.setUser("Admin_user")
zab.setPassword("Admin_password")
if zab.login() == True:
    create_resp = zab.createUser("zezinho", "teste", local.ZABBIX_USRGRPID)
    if create_resp:
        jresp = json.loads(create_resp)
        userids = int(jresp['result']['userids'][0])
        print userids
    else:
        print create_resp
Example #16
0
    SETTINGS = config['settings']
    exit_status = 0

    # Set Logging
    log_level = logging.getLevelName(SETTINGS['log_level'])
    log_level_requests = logging.getLevelName(SETTINGS['log_level_requests'])
    logging.basicConfig(
        level=log_level,
        format='%(asctime)s %(levelname)s: (%(threadName)s) %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S %Z')
    logging.getLogger("requests").setLevel(log_level_requests)
    logging.info('Zabbix Cachet v.{} started'.format(__version__))
    inc_update_t = threading.Thread()
    event = threading.Event()
    try:
        zapi = Zabbix(ZABBIX['server'], ZABBIX['user'], ZABBIX['pass'],
                      ZABBIX['https-verify'])

        cachet = Cachet(CACHET['server'], CACHET['token'],
                        CACHET['https-verify'])

        zbxtr2cachet = ''

        # Create mapping between metrics and IT services
        metrics_mapping = init_metrics(SETTINGS['metric_services'])

        # Run metric updater
        metric_update_t = threading.Thread(
            name='Metrics Updater',
            target=metrics_updater_worker,
            args=(metrics_mapping, SETTINGS['update_metric_interval']))
Example #17
0
    def read(self, request):

        api_obs = u"Adição de usuário"
        api_log_referencia_id = None
        api_log_action_nome = "criar"
        api_log_tipo_nome = "usuario"

        alog = Log.saveAlog(request)

        #gerando nome
        NAME_LENGTH = 10
        NAME_CHARS = "abcdefghjkmnpqrstuvwxyz23456789"
        nome_hash = User.objects.make_random_password(length=NAME_LENGTH,
                                                      allowed_chars=NAME_CHARS)

        usuario_nome = str(nome_hash)
        usuario_contrato = request.GET.get("contrato")
        usuario_usuario = request.GET.get("usuario")
        usuario_label = request.GET.get("label")
        usuario_servidor = request.GET.get("servidor")
        usuario_email = request.GET.get("email")
        usuario_senha = request.GET.get("senha")

        #validando parametros
        if filter(lambda value: not value or value is None, [
                usuario_label, usuario_usuario, usuario_email, usuario_senha,
                usuario_contrato, usuario_servidor
        ]):
            return raiseError(alog, "param_missing", request, None, api_obs,
                              api_log_referencia_id, api_log_action_nome,
                              api_log_tipo_nome)

        #buscando id do servidor
        try:
            servidor = Servidor.objects.get(nome=usuario_servidor)
        except ObjectDoesNotExist:
            return raiseError(alog, "server_not_exist", request, None, api_obs,
                              api_log_referencia_id, api_log_action_nome,
                              api_log_tipo_nome)
        else:
            usuario_servidor = servidor.id

        usuario = Usuario.objects.filter(usuario=usuario_usuario)
        email = Usuario.objects.filter(email=usuario_email)

        #verificando se usuario ou e-mail existem
        if usuario:
            return raiseError(alog, "user_exist", request, None, api_obs,
                              api_log_referencia_id, api_log_action_nome,
                              api_log_tipo_nome)
        elif email:
            return raiseError(alog, "email_exist", request, None, api_obs,
                              api_log_referencia_id, api_log_action_nome,
                              api_log_tipo_nome)
        error_transaction = None

        # valores caso nao consiga incluir no Zabbix
        usuario_tentativa = 1
        status = Status.objects.get(label='INCLUIR')
        userids = 0

        # tentando incluir no Zabbix
        try:
            zab_usuario = local.SERVER_ZABBIX[servidor.nome]['usuario']
            zab_senha = local.SERVER_ZABBIX[servidor.nome]['senha']
            zab = Zabbix()
            zab.setHost(servidor.endereco)
            zab.setUser(zab_usuario)
            zab.setPassword(zab_senha)
            if zab.login() == True:
                create_resp = zab.createUser(usuario_email, usuario_senha,
                                             local.ZABBIX_USRGRPID)
                if create_resp:
                    jresp = json.loads(create_resp)
                    userids = int(jresp['result']['userids'][0])
                    status = Status.objects.get(label='ATIVO')
                    usuario_tentativa = 0
        except:
            pass

        #incluindo
        with transaction.commit_manually():
            try:
                usuario = Usuario(nome=usuario_nome,
                                  usuario=usuario_usuario,
                                  label=usuario_label,
                                  servidor=servidor,
                                  email=usuario_email,
                                  zabbix_id=userids,
                                  senha=usuario_senha,
                                  contrato=usuario_contrato,
                                  tentativa=usuario_tentativa,
                                  status=status,
                                  data_criacao=datetime.datetime.now())
                usuario.save()

            except Exception, error:
                error_transaction = error
                transaction.rollback()

            else:
Example #18
0
    def Add(self, request):
        api_obs = u"Inclusao de item no Zabbix"
        api_log_referencia_id = None
        api_log_action_nome = "criar"
        api_log_tipo_nome = "zab"
        alog = Log.saveAlog(request)

        #buscando id do servidor
        try:
            servidor = Servidor.objects.get(nome=local.SERVER_ZABBIX_DEFAULT)
        except ObjectDoesNotExist:
            return raiseError(alog, "server_not_exist", request, None, api_obs,
                              api_log_referencia_id, api_log_action_nome,
                              api_log_tipo_nome)
        else:
            self.usuario_servidor = servidor.id

        try:
            host = Host.objects.get(nome=self.nome)
        except ObjectDoesNotExist:
            return raiseError(alog, "host_not_exist", request, None, api_obs,
                              api_log_referencia_id, api_log_action_nome,
                              api_log_tipo_nome)
        else:
            host_id = host.id

        # valores caso nao consiga incluir item no Zabbix
        error_transaction = None
        self.tentativa = 1
        status = Status.objects.get(label='INCLUIR')
        itemids = 0

        # tentando incluir item no Zabbix
        try:
            zab_usuario = local.SERVER_ZABBIX[servidor.nome]['usuario']
            zab_senha = local.SERVER_ZABBIX[servidor.nome]['senha']
            zab = Zabbix()
            zab.setHost(servidor.endereco)
            zab.setUser(zab_usuario)
            zab.setPassword(zab_senha)

            if zab.login() == True:
                interfaceIds = zab.getHostInterface(self.hostids)
                for a in interfaceIds:
                    if str(a['hostid'] == self.hostids):
                        interface_id = a['interfaceid']

                create_resp = zab.createPingItem(self.label, int(self.hostids),
                                                 int(interface_id))
                if create_resp:
                    jresp = json.loads(create_resp)
                    itemids = int(jresp['itemids'][0])
                    status = Status.objects.get(label='ATIVO')
                    self.tentativa = 0
        except:
            pass

        #incluindo item no mysql
        with transaction.commit_manually():
            try:
                item = Item(nome=self.nome,
                            label=self.label,
                            tentativa=self.tentativa,
                            status=status,
                            host=host,
                            zabbix_id=itemids,
                            data_criacao=datetime.datetime.now())
                item.save()
            except Exception, error:
                error_transaction = error
                transaction.rollback()
            else: