Exemple #1
0
def get(user, password, template, url):
    zabbix = ZabbixAPI(url=url, user=user, password=password)
    f = zabbix.do_request('template.get', {'filter': {'host': template},'output': 'templateid'})
    templateid = f['result'][0]['templateid']
    item = zabbix.do_request('item.get',{'templateids': templateid,'output': 'extend'})
    for n in item['result']:
         dict_item.update({ n['name']: n['key_']})
    triggers = zabbix.do_request('trigger.get',{'templateids': templateid,'output': 'extend'})
    for n in triggers['result']:
        dict_trigger.update({ n['triggerid']: n['description']})
    zabbix.user.logout()
Exemple #2
0
def add_monitor(hostname, url=config.XG_URL, auth=config.XG_AUTH):
    try:
        zabbix_api = ZabbixAPI(url=url, use_auth=True, auth=auth)
        hosts_id = zabbix_api.do_request('host.get', params={'output':'hostid', 'filter':{'host':[hostname]}})

        if url==config.XG_URL:
            zabbix_api.do_request('host.massadd', params={'hosts': hosts_id['result'],
                            'templates': config.XG_TEMPLATE_IDS})
        else:
            zabbix_api.do_request('host.massadd', params={'hosts': hosts_id['result'],
                            'templates': config.QC_TEMPLATE_IDS})
    except Exception,e:
        pass
def ack():
    eventid = int(unquote(request.args['eventid']).replace("'", ''))
    taskid = request.args['taskid']
    action = app.config['ACTION']
    #login to zabbix
    zapi = ZabbixAPI(url=app.config['URL'],
                     user=app.config['USER'],
                     password=app.config['PWD'])
    #acknowledge alert
    zapi.do_request(
        'event.acknowledge', {
            'eventids': eventid,
            'action': action,
            'message':
            'ServiceNow has created {} for this alert'.format(taskid)
        })
    #logut zabbix
    zapi.do_request('user.logout')
    return 'ok'
class Zabbix_Api:
    def __init__(self, idc='qc'):
        qc_url = ''
        xg_url = ''
        qc_auth = ''
        xg_auth = ''
        self.url = qc_url if idc == 'qc' else xg_url
        self.auth = qc_auth if idc == 'qc' else xg_auth

        self.z = ZabbixAPI(url=self.url, use_auth=True, auth=self.auth)

    def Get_Token(self, user=None, password=None):
        try:
            token = self.z._login(user=user, password=password)
            return token
        except Exception as e:
            print(e)

    # 获取id,支持扩展获取所有id
    def Get_ID(self,
               HostName=None,
               Template=None,
               ScreenName=None,
               Action='filter',
               Macros_Flag=False,
               Filter_Flag=False):
        if HostName and len(HostName) <= 6:
            exit('Warning: Hostname so short')
        if HostName and '*' in HostName:
            HostName = ''.join(HostName.split('*'))
            Filter_Flag = True

        Get_Input = HostName or Template or ScreenName
        Host_List = []
        Host_ID = []
        Template_List = []
        Template_ID = []
        Screen_ID = []
        Screen_List = []
        try:
            for l in Get_Input.split(','):
                if HostName:
                    Host_List.append(l)
                elif Template:
                    Template_List.append(l)
                elif ScreenName:
                    Screen_List.append(l)
            if Host_List:
                # 模糊匹配与精确查询
                Action = 'search' if Filter_Flag else Action
                # Group_Flag = True if GroupName else Group_Flag
                for h in Host_List:
                    host_id = self.z.do_request('host.get',
                                                params={'output': ['host', 'hostid'], "%s" % Action: {'host': h}})
                    res = sorted(host_id['result'], key=lambda x: int(x['host'].split('-')[-1]))
                    for i in res:
                        del i['host']
                        Host_ID.append(i)
                return Host_ID

            elif Template_List:
                for t in Template_List:
                    if Macros_Flag:
                        re = self.z.do_request('template.get',
                                               params={'selectMacros': ['macro', 'value'], 'filter': {'host': t}})
                        macros = re['result'][0]['macros']
                        for i in macros:
                            i.pop('hosts')
                        data = re['result']
                        Template_ID.extend(data)
                    re = self.z.do_request('template.get', params={'output': 'templateid', 'filter': {'host': t}})
                    data = re['result']
                    Template_ID.extend(data)
                return Template_ID
            elif Screen_List:
                for s in Screen_List:
                    re = self.z.do_request('screen.get', params={'output': 'screenid', 'filter': {'name': s}})
                    Screen_ID.append(re['result'][0]['screenid'])
                return Screen_ID

        except Exception as e:
            print(e)

    def Get_GroupID(self, GroupName=None):
        try:
            Group_ID = self.z.do_request('hostgroup.get', params={'output': 'extend', 'filter': {'name': GroupName}})
            return Group_ID['result'][0]['groupid']
        except Exception as e:
            print(e)

    def Get_GraphID(self, HostName=None, GraphName=None, Columns=3):
        Graph_ID = []
        Graph_List = []
        x = 0
        y = 0
        try:
            Host_ID = self.Get_ID(HostName=HostName)
            Only_Host_ID = map(lambda x: x.values()[0], Host_ID)
            for hostid in Only_Host_ID:
                re_graphid = self.z.do_request('graph.get',
                                               params={'output': ['graphid'],
                                                       'hostids': hostid,
                                                       'softfield': 'graphid', 'search': {'name': GraphName}})
                if re_graphid['result']:
                    Graph_ID.append(re_graphid['result'][0]['graphid'])
                else:
                    exit('Some host not have the graph: "%s" !' % GraphName)
            for graph in Graph_ID:
                Graph_List.append({
                    'resourcetype': '0',
                    'resourceid': graph,
                    'width': '500',
                    'height': '200',
                    'x': str(x),
                    'y': str(y),
                    'colspan': '0',
                    'rowspan': '0',
                    'elements': '0',
                    'valign': '0',
                    'halign': '0',
                    'style': '0',
                    'url': '',
                    'dynamic': '0'
                })
                x += 1
                if x == int(Columns):
                    x = 0
                    y += 1
            return Graph_ID, Graph_List
        except Exception as e:
            print(e)

    def Screen_Create(self, HostName=None, GraphName=None, ScreenName=None, Columns=3):
        try:
            Graph_ID, Graph_List = self.Get_GraphID(HostName=HostName, GraphName=GraphName)
            if len(Graph_ID) % Columns == 0:
                vsize = len(Graph_ID) / Columns
            else:
                vsize = (len(Graph_ID) / Columns) + 1

            Screen_ID = self.Get_ID(ScreenName=ScreenName)[0]
            if Screen_ID:
                re = self.z.do_request('screen.update', params={'screenid': Screen_ID,
                                                                'name': ScreenName,
                                                                'screenitems': Graph_List,
                                                                'hsize': Columns,
                                                                'vsize': vsize})
                if re['result']['screenids']:
                    print('The screen : "%s" has been update!' % ScreenName)
            else:
                re = self.z.do_request('screen.create',
                                       params={'name': ScreenName, 'hsize': Columns, 'vsize': vsize,
                                               'screenitems': Graph_List})
                if re['result']['screenids']:
                    print('The screen name: "%s" create succeed!' % ScreenName)
                    sys.exit(0)
                exit('Screen create failed')
        except Exception as e:
            print(e)

    def Create_Template(self, TemplateName=None, LinkTemplate=None, Template_ID=None, Macros=None):
        try:
            if LinkTemplate:
                Template_Info = self.Get_ID(Template=LinkTemplate, Macros_Flag=True)[0]
                Template_ID = Template_Info['templateid']
                Macros = Template_Info['macros']
            re = self.z.do_request('template.create',
                                   params={'host': TemplateName, 'groups': {'groupid': 1},
                                           'templates': Template_ID,
                                           'macros': Macros})
            if re['result']['templateids']:
                print('Template "%s" create succeed!' % TemplateName)
        except Exception as e:
            print(e)

    def Delete_Template(self, TemplateName=None):
        Template_List = []
        try:
            Template_ID = self.Get_ID(Template=TemplateName)[0]['templateid']
            Template_List.append(Template_ID)
            re = self.z.do_request('template.delete', params=Template_List)
            if re['result']['templateids']:
                print('Template "%s" has been delete!' % TemplateName)
        except Exception as e:
            print(e)

    def Mass_Remove_Templates(self, HostName=None, Templates=None):
        data = []
        try:
            Host_ID = self.Get_ID(HostName=HostName)
            Only_Host_ID = map(lambda x: x.values()[0], Host_ID)
            for t in Templates.split(','):
                Template_ID = self.Get_ID(Template=t)[0]['templateid']
                re = self.z.do_request('host.massremove',
                                       params={'hostids': Only_Host_ID, 'templateids_clear': Template_ID})
                data.append(re['result'])
            if data:
                print('template has been unlink!')
                sys.exit(0)
            exit('template unlink failure!')
        except Exception as e:
            print(e)

    def Mass_Add_Templates(self, HostName=None, Templates=None):
        Templates_List = []
        data = []
        try:
            Host_ID = self.Get_ID(HostName=HostName)
            for t in Templates.split(','):
                Templates_ID = self.Get_ID(Template=t)
                Templates_List.extend(Templates_ID)
                re = self.z.do_request('host.massadd', params={'hosts': Host_ID, 'templates': Templates_List})
                data.append(re['result'])
            if data:
                print('Template has been link!')
                sys.exit(0)
            exit('Template link failure!')
        except Exception as e:
            print(e)

    def Mass_Groups(self, HostName=None, GroupName=None, Method=None):
        Group_ID = self.Get_GroupID(GroupName=GroupName)
        Hosts_ID = self.Get_ID(HostName=HostName)
        Only_Host_ID = map(lambda x: x.values()[0], Hosts_ID)
        Mass = 'host.mass'
        try:
            if Method == 'replace':
                Method = Mass + 'update'
            elif Method == 'add':
                Method = Mass + 'add'
            re = self.z.do_request(Method, params={'hosts': Hosts_ID, 'groups': [{'groupid': Group_ID}]})
            if re['result']['hostids']:
                print('hosts information has been updated!')
            elif Method == 'remove':
                re = self.z.do_request('host.massremove', params={'hostids': Only_Host_ID, 'groupids': Group_ID})
                if re['result']['hostids']:
                    print('hosts information has been updated!')

        except Exception as e:
            print(e)

    def Method(self, ScreenName=None):
        try:
            Screen_ID = self.Get_ID(ScreenName=ScreenName)
            re = self.z.do_request('screen.delete', params=Screen_ID)['result']['screenids']
            if re:
                print('%s has been delete' % ScreenName)
                sys.exit(0)
            print('The given screen name: "%s" not exists' % ScreenName)
        except Exception as e:
            print(e)

    def Disable_Host(self, HostName=None, Method=None):
        status = 0
        data = []
        try:
            status = 1 if Method == 'disable' else status
            Hostids = self.Get_ID(HostName=HostName)
            if not Hostids:
                exit('"%s" not exists!' % HostName)
            for h in Hostids:
                re = self.z.do_request('host.massupdate', params={'hosts': h, 'status': status})
                data.append(re['result']['hostids'])
            if not data:
                exit('"%s" failed!' % Method)
            print('hosts has been "%s" !' % Method)
        except Exception as e:
            print(e)

    def main(self):
        if len(sys.argv) == 1:
            parse.print_help()
        else:
            args = parse.parse_args()
            Method = ['delete', 'disable', 'enable', 'replace', 'remove', 'add', 'create']
            # print(args)
            if args.idc == 'xg':
                self.__init__(idc='xg')
            if args.method_link == 'unlink' and args.template and args.hostname:
                self.Mass_Remove_Templates(HostName=args.hostname, Templates=args.template)
            elif args.method_link == 'link' and args.template and args.hostname:
                self.Mass_Add_Templates(HostName=args.hostname, Templates=args.template)
            elif args.screen and args.hostname and args.graph:
                self.Screen_Create(HostName=args.hostname, GraphName=args.graph, ScreenName=args.screen)
            elif args.graph and args.hostname:
                self.Get_GraphID(HostName=args.hostname, GraphName=args.graph)
            elif args.method:
                if args.screen and args.method in Method:
                    self.Method(ScreenName=args.screen)
                elif args.group and args.hostname and args.method in Method:
                    self.Mass_Groups(HostName=args.hostname, GroupName=args.group, Method=args.method)
                elif args.method == 'create' and args.template or args.link_template:
                    self.Create_Template(TemplateName=args.template, LinkTemplate=args.link_template)
                elif args.method == 'delete' and args.template:
                    self.Delete_Template(TemplateName=args.template)
                elif args.hostname and args.method in Method:
                    self.Disable_Host(HostName=args.hostname, Method=args.method)
            elif args.hostname or args.template:
                re = self.Get_ID(HostName=args.hostname, Template=args.template)
                print(re)
Exemple #5
0
                        metavar="IP")
    parser.add_argument('--snmpsim-port',
                        dest="snmpsim_port",
                        default="161",
                        help="UDP port of the snmpsim server.",
                        metavar="161")
    args = parser.parse_args()

    try:
        zapi = ZabbixAPI(url=args.api_url,
                         user=args.username,
                         password=args.password)
    except ZabbixAPIException as err:
        print(err.data)

    else:
        path = args.arg1[0]
        if os.path.isdir(path):
            # snmpsim
            snmpsim_create = SnmpsimCreator(path, zapi, args.filter_str,
                                            args.snmpsim_ip, args.snmpsim_dns,
                                            args.snmpsim_port)
            snmpsim_create.scan_snmpsim_root_dir()

            hosts_create = HostsCreator(path, zapi, args.filter_str)
            hosts_create.scan_snmpsim_root_dir()
        else:
            sys.exit("{0} is not a valid directory".format(path))

        zapi.do_request('user.logout')
Exemple #6
0
import os
from pyzabbix.api import ZabbixAPI

# Create ZabbixAPI class instance
pasted_URL = 'http://' + str(os.environ["MASTER_NODE_IP_PUBLIC"]) + '/zabbix/'
zapi = ZabbixAPI(url=str(pasted_URL), user='******', password='******')

node_name_removed = str(os.environ["NODE_NAME_REMOVED"])

# Get dictionary of host to be deleted
result_removed_host_id = zapi.do_request(
    'host.get', {'filter': {
        'name': [node_name_removed]
    }})

# Get id of host to be deleted
parsed_removed_host_id = result_removed_host_id['result'][0]['hostid']

# Delete node based on its id
result_delete_node = zapi.do_request('host.delete', [parsed_removed_host_id])

# Logout from Zabbix
zapi.user.logout()
Exemple #7
0
def main():

    changed = False

    module = AnsibleModule(supports_check_mode=False,
                           argument_spec={
                               "url": {
                                   "type": "str",
                                   "required": True
                               },
                               "default_password": {
                                   "type": "str",
                                   "required": False,
                                   "default": "zabbix",
                                   "no_log": True
                               },
                               "login_password": {
                                   "type": "str",
                                   "required": True,
                                   "no_log": True
                               },
                               "users": {
                                   "type": "list",
                                   "required": False,
                                   "no_log": False
                               }
                           })

    try:
        zapi = ZabbixAPI(
            **{
                'url': module.params['url'],
                'user': '******',
                'password': module.params['default_password']
            })

        admin_userid = get_userid_by_name(username='******', zapi=zapi)

        change_password(userid=get_userid_by_name('Admin', zapi),
                        new_passwd=module.params['login_password'],
                        zapi=zapi)

        changed = True
        sleep(0.1)
        zapi.user.logout()
    except ZabbixAPIException as e:
        pass

    try:
        zapi = ZabbixAPI(
            **{
                'url': module.params['url'],
                'user': '******',
                'password': module.params['login_password']
            })

        users_list = [
            i["alias"] for i in zapi.do_request("user.get")["result"]
        ]

        for user in module.params['users']:
            if user["name"] not in users_list:
                if not create_user(username=user['name'],
                                   password=user['password'],
                                   user_type=user['type'],
                                   groups=user["groups"],
                                   zapi=zapi):
                    return module.fail_json(msg=e.message, json=e.json)
                else:
                    changed = True
                    users_list = [
                        i["alias"]
                        for i in zapi.do_request("user.get")["result"]
                    ]
                    continue

            if not is_credentials_valid(
                    **{
                        'url': module.params['url'],
                        'user': user['name'],
                        'password': user['password']
                    }):
                changed = True
                change_password(userid=get_userid_by_name(user['name'], zapi),
                                new_passwd=user['password'],
                                zapi=zapi)
                sleep(0.1)

            if not update_user(username=user['name'],
                               password=user['password'],
                               user_type=user['type'],
                               groups=user["groups"],
                               zapi=zapi):
                return module.fail_json(msg=e.message, json=e.json)

        sleep(0.1)
        zapi.user.logout()
    except ZabbixAPIException as e:
        return module.fail_json(msg=e.message, json=e.json)

    result = {"changed": changed}

    module.exit_json(**result)
Exemple #8
0
try:
    zapi = ZabbixAPI(url=url, user=username, password=password)
    print ('Auth Ok!')
except Exception as err:
    print('Erro ao conectar ao Zabbix')
    print('Erro: {}'.format(err))


hostname = 'CL-MATEUS-MAIOBAO-14.162'


gethost = zapi.do_request('host.get',
                            {
                                "filter": {
                                    "host": [
                                        hostname
                                    ]
                                }
                            }
                        )


'''
request = zapi.do_request('problem.get',
                            {
                                "output": "extend",
                                #"selectAcknowledges": "extend",
                                "selectTags": "extend",
                                "selectSuppressionData": "extend",
                                "hostids": gethost['result'][0]["hostid"],
                                "recent": "false",
try:
        newincno = newinc["records"][0]["number"]
except:
        print ("unable to retrieve new incident number\n")
#f.write("unable to retrieve new incident number\n")

zapi = 
ZabbixAPI(url='http://'+zabbixsrv+'/zabbix',user=zabbixun,password=zabbixpw)
#zapi.user.login()
#f.write('Acknowledging event '+eventid+'\n')
#zapi.Event.acknowledge({'eventids':[eventid],'message':newincno})

# Get all monitored hosts
result1 = zapi.host.get(monitored_hosts=1, output='extend')
# Get all disabled hosts
result2 = zapi.do_request('host.get',
                              {
                                  'filter': {'status': 1},
                                  'output': 'extend'
                              })

# Filter results
hostnames1 = [host['host'] for host in result1]
hostnames2 = [host['host'] for host in result2['result']]

# Logout from Zabbix
zapi.user.logout()

#f.write('\n\nScript End :: '+datetime.datetime.now().ctime()+'\n\n')
#f.close()
Exemple #10
0
import json

zabbix = {}
with open(f'conf.json', 'r') as confs:
    zabbix = json.loads(confs.read())

try:
    zapi = ZabbixAPI(url=zabbix['url'],
                     user=zabbix['username'],
                     password=zabbix['password'])
    print('Auth Ok!')
except Exception as err:
    print('Erro ao conectar ao Zabbix')
    print('Erro: {}'.format(err))

getHostGroup = zapi.do_request(
    'item.get', {
        "filter": {
            "state": 1
        },
        "output": ["hostid", "name", "itemid"],
        "monitored": True
    })
i = 0
for item in getHostGroup["result"]:
    i += 1
    print(f"Item {i} --> {item}")

for x in getHostGroup["result"]:
    zapi.do_request('item.update', {"itemid": x['itemid'], "status": 1})
Exemple #11
0
import os
from pyzabbix.api import ZabbixAPI

# Create ZabbixAPI class instance
pasted_URL = 'http://' + str(os.environ["MASTER_IP_PUBLIC"]) + '/zabbix/'
zapi = ZabbixAPI(url=str(pasted_URL), user='******', password='******')

# Create new hostgroup
result1 = zapi.do_request('hostgroup.create',
                          {'name': 'Unicore compute nodes'})

# Get id of newly created hostgroup
parsed_group_id_unicore = result1['result']['groupids'][0]

# Get dictionary of discovered hostgroup
result_discovered_host_groups = zapi.do_request(
    'hostgroup.get', {'filter': {
        'name': ['Discovered hosts']
    }})

# Get id of discovered hostgroup
parsed_group_id_discovered = result_discovered_host_groups['result'][0][
    'groupid']

# Get templateid of Linux Template
result2 = zapi.do_request('template.get',
                          {'filter': {
                              'host': ['Template OS Linux']
                          }})

parsed_template_id = result2['result'][0]['templateid']
class GeneralZabbix:
    def __init__(self, sHostName, sZabbixIP, iZabbixPort, sZabUser, sZabPwd):
        """
        sHostName is a name of host or array (HOST.HOST) IN ZABBIX
        *Zab* are parameters for Zabbix connection.
        """
        # oLog.debug("Entered GeneralZabbix.__init__")
        self.sZabbixURL = 'http://' + sZabbixIP + "/zabbix"
        self.sZabbixIP = sZabbixIP
        self.iZabbixPort = iZabbixPort
        self.dApplicationNamesToIds = {}
        self.sHostName = sHostName
        self.ldApplications = []
        self.dItemNames = {}
        self.dAppIds = {}
        self.dApps = {}
        # self.sArrayName = sHostName
        self.sHostID = ''
        self.iHostID = 0
        try:
            self.oZapi = ZabbixAPI(url=self.sZabbixURL, user=sZabUser, password=sZabPwd)
            self.oAPI = self.oZapi
            self.oZSend = ZabbixSender(zabbix_server=self.sZabbixIP, zabbix_port=self.iZabbixPort)
            lsHosts = self.oZapi.host.get(filter={"host": sHostName})
            if len(lsHosts) > 0:
                # Just use the first host
                self.sHostID = str(lsHosts[0]['hostid'])
                self.iHostID = int(self.sHostID)
                oLog.debug("host ID of host {1}: {0}".format(self.sHostID, self.sHostName))
            else:
                oLog.error("Invalid or non-existent host in Zabbix")
                raise ZabInterfaceException("This host '{}' isn't known to Zabbix".format(sHostName))
        except ZabbixAPIException as e:
            oLog.error("Cannot connect to Zabbix API")
            oLog.error(str(e))
            raise ZabInterfaceException
        return

    def __fillApplications__(self, reFilter=None):
        # receive the list of applications
        ldApplications = self.oZapi.do_request('application.get', {'hostids': self.sHostID})
        ldAppResult = ldApplications['result']
        dBuf = {}
        if len(ldAppResult) == 0:
            # the host exists but didn't return anything, just continue
            oLog.info("Array with ID {0} and name {1} doesn't answer".format(self.sHostID, self.sHostName))
        else:
            # oLog.debug("Applications on host {0}: {1}".format(self.sArrayName, ldAppResult))
            # now filter the apps list for this host
            for dApp in ldAppResult:
                sAppName = dApp['name']
                if reFilter:
                    if reFilter.match(sAppName):
                        dBuf[sAppName] = dApp['applicationid']
                        # oLog.debug('__fillApplications__: found app {}'.format(sAppName))
                    else:
                        # oLog.debug("__fillApplications__: skipped app {}".format(sAppName))
                        pass
                else:
                    dBuf[sAppName] = dApp['applicationid']
            self.dApplicationNamesToIds = dBuf
        return

    def _oPrepareZabMetric(self, sAppName, sParameter, iValue):
        """Prepare ZabbixMetric instance for sending to a Zabbix server"""
        dFilter = {'name': sAppName + ' ' + sParameter}
        try:
            iAppID = self.dApplicationNamesToIds[sAppName]
            dItem2Get = {'hostids': self.sHostID,
                         'applicationids': iAppID,
                         'filter': dFilter,
                         'sort': 'name'}
            dResult = self.oZapi.do_request('item.get', dItem2Get)
            try:
                sKey = dResult['result'][0]['key_']
                # now we have key, so we can prepare data to Zabbix
                oRet = ZabbixMetric(host=self.sHostName, key=sKey, value=iValue)
            except IndexError:
                oLog.info("Can't receive item named '{}' from Zabbix with item.get".format(dFilter['name']))
                oRet = None
        except KeyError:
            oLog.info('Unknown application name "{}"'.format(sAppName))
            # oLog.info('Known apps: ' + str(self.dApplicationNamesToIds))
            oRet = None
        return oRet

    def _SendMetrics(self, loMetrics):
        """Send only non-empty metrics to Zabbix"""
        if loMetrics:
            # skip empty objects from loMetrics
            loMetrics = [o for o in loMetrics if o is not None]
            self.oZSend.send(loMetrics)
        else:
            pass   # dont send empty metrics
        return

    def _iGetHostID(self):
        return int(self.sHostID)

    def _sName(self):
        return self.sHostName

    def _bHasApplication(self, sAppName):
        sAppName = sAppName.lower()
        ldApplications = self.oZapi.do_request('application.get', {'hostids': self.sHostID})
        for dApp in ldApplications['result']:
            sNewName = dApp['name'].lower()
            sNewID = dApp['applicationid']
            self.dAppIds[sNewName] = dApp['applicationid']
            self.dApps[sNewID] = ZabbixApplication(sNewName, self, dApp)
        bRet = (sAppName in self.dAppIds)
        return bRet

    def _bHasItem(self, sItemName):
        bRet = False
        sItemName = sItemName.lower()
        if sItemName in self.dItemNames:
            bRet = True
        else:
            # try to refresh dItemNames
            dGetItem = {'hostids': self.iHostID,
                        'search': {'name': sItemName}}
            dItems = self.oAPI.do_request('item.get', dGetItem)
            # oLog.debug('_bHasItem: result of item.get() is {}'.format(str(dItems)))
            if len(dItems['result']) > 0:
                # matching item(s) found
                for dItemDict in dItems['result']:
                    # dItemDict = dItems['result'][0]
                    # oLog.debug("Item found: {}".format(str(dItemDict)))
                    sName = dItemDict['name'].lower()
                    dItemDict['key'] = dItemDict.get('key_')    # from the Zabbix parameter 'key_'
                    self.dItemNames[sName] = ZabbixItem(sName, self, dItemDict)
                bRet = True
            else:
                # No item found
                bRet = False
            # oLog.debug('_bHasItem: dItemNames after call is: ' + str(self.dItemNames))
        return bRet

    def _oGetItem(self, sItemName):
        """returns item object by name"""
        sItemName = sItemName.lower()
        if self._bHasItem(sItemName):
            return self.dItemNames.get(sItemName, None)
        else:
            return None

    def _oGetApp(self, sAppName):
        sAppName = sAppName.lower()
        if self._bHasApplication(sAppName):
            return self.dApps[self.dAppIds[sAppName]]
        else:
            return None

    def _oAddApp(self, sAppName):
        # sAppName = sAppName.lower()
        if self._bHasApplication(sAppName):
            # already have this app
            oApp = self._oGetApp(sAppName)
        else:
            oApp = ZabbixApplication(sAppName, self)
            oApp._NewApp(sAppName)
            self.dAppIds[sAppName] = oApp._iGetID
            self.dApps[oApp._iGetID] = oApp
        return oApp

    def _oAddItem(self, sItemName, sAppName='', dParams=None):
        # sItemName = sItemName.lower()
        if self._bHasItem(sItemName):
            # already have that item
            oItem = self._oGetItem(sItemName)
            oLog.debug('Already have that item, returned {}'.format(str(oItem)))
        else:
            # need to create item
            oItem = ZabbixItem(sItemName, self, dParams)
            self.dItemNames[sItemName] = oItem
            if sAppName != '':
                oApp = self._oGetApp(sAppName)
                oItem._LinkWithApp(oApp)
            oItem._NewZbxItem()
            oLog.debug('Created a new item, returned {}'.format(str(oItem)))
        return oItem

    def _MakeTimeStamp(self):
        """make an application and item (if there are no), send current timestamp as a TS of last update"""
        sTSAppName = 'Timestamps'
        sItemName = 'Last updated'
        if not self._bHasApplication(sTSAppName):
            self._oAddApp(sTSAppName)
        if self._bHasItem(sItemName):
            oTimeStamp_Item = self._oGetItem(sItemName)
            oLog.debug('Timestamp item: ' + str(oTimeStamp_Item))
        else:
            oTimeStamp_Item = self._oAddItem(
                sItemName, sAppName=sTSAppName,
                dParams={'key': "Update_Time", 'value_type': 3, 'units': 'unixtime',
                         'description': 'Date and time of last data update'})
        # now the application and item must exist
        oTimeStamp_Item._SendValue(int(time.time()), self.oZSend)
        oLog.debug('TimeStamp set!')
        return

    def _SendInfoToZabbix(self, sArrayName, ldInfo):
        """send data to Zabbix via API"""
        loMetrics = []
        # oLog.debug('sendInfoToZabbix: data to send: {}'.format(str(ldInfo)))
        for dInfo in ldInfo:
            if self.sAppClass == 'System':   # Special case
                sAppName = self.sAppClass
            else:
                sAppName = (self.sAppClass + ' ' + dInfo['name']).strip()
            for sName, oValue in dInfo.items():
                try:
                    loMetrics.append(self.dOperations[sName](sAppName, oValue))
                except KeyError:
                    # unknown names passed
                    oLog.info('Skipped unknown information item named {} with value {}'.format(
                        sName, str(oValue)))
                    pass
        self._SendMetrics(loMetrics)
        return
Exemple #13
0
import os
from pyzabbix.api import ZabbixAPI

# Create ZabbixAPI class instance
pasted_URL = 'http://' + str(os.environ["MASTER_IP_PUBLIC"]) + '/zabbix/'
zapi = ZabbixAPI(url=str(pasted_URL), user='******', password='******')

# Create new hostgroup
result1 = zapi.do_request('hostgroup.create',
                          {'name': 'Unicore compute nodes'})

# Get id of newly created hostgroup
parsed_group_id_unicore = result1['result']['groupids'][0]

# Get dictionary of discovered hostgroup
result_discovered_host_groups = zapi.do_request(
    'hostgroup.get', {'filter': {
        'name': ['Discovered hosts']
    }})

# Get id of discovered hostgroup
parsed_group_id_discovered = result_discovered_host_groups['result'][0][
    'groupid']

# Get templateid of Linux Template
result2 = zapi.do_request('template.get',
                          {'filter': {
                              'host': ['Template OS Linux']
                          }})

parsed_template_id = result2['result'][0]['templateid']
class ZapiHelper(object):
    def __init__(self, zbx_api_config):
        self.zapi_url = zbx_api_config.get('zapi_url', 'zapi_url')
        self.zapi_user = zbx_api_config.get('user', 'user')
        self.zapi_password = zbx_api_config.get('password', 'password')
        self.supported_api_major_versions = ['3.4']
        self.output_formats = ['refer', 'shorten', 'extend']
        self.import_export_formats = ['xml', 'json']
        self.__init_api()

    def __validate_api_versions(self, api_v):
        """check supported api versions"""
        if api_v[0:3] not in self.supported_api_major_versions:
            msg = 'Unsupported api version {0}.' \
                  'Supported versions are: {1}' \
                  .format(api_v[0:3], self.supported_api_major_versions)
            raise RuntimeError(msg)

    def __validate_output_format(self, out_format):
        """check supported output format"""
        if out_format not in self.output_formats:
            msg = 'Unsupported output format {0}.' \
                  'Supported formats are: {1}' \
                  .format(out_format, self.output_formas)
            raise RuntimeError(msg)

    def __valide_export_format(self, export_format):
        """check supported export format"""
        if export_format not in self.import_export_formats:
            msg = 'Unsupported export format {0}.' \
                  'Supported formats are: {1}' \
                  .format(export_format, self.import_export_formats)
            raise RuntimeError(msg)

    def __valide_import_format(self, import_format):
        """check supported import format"""
        if import_format not in self.import_export_formats:
            msg = 'Unsupported import format {0}.' \
                  'Supported formats are: {1}' \
                  .format(import_format, self.import_export_formats)
            raise RuntimeError(msg)

    def __init_api(self):
        self.zapi = ZabbixAPI(self.zapi_url,
                              user=self.zapi_user,
                              password=self.zapi_password)
        self.zapi_version = self.__validate_api_versions(
            self.zapi.do_request('apiinfo.version')['result'])

    def get_hosts(self, hosts=[], output='extend'):
        """ get hosts from zabbix api
            if hosts=[] return all hosts
        """
        self.__validate_output_format(output)
        hosts = self.zapi.host.get(filter={'host': hosts}, output=output)
        return hosts

    def get_templates(self, templates=[], output='extend'):
        """ get templates from zabbix api
            if templates=[] return all templates
        """
        self.__validate_output_format(output)
        templates = self.zapi.template.get(filter={'host': templates},
                                           output=output)
        res = {i['name']: i['templateid'] for i in templates}
        return res

    def api_export(self, export_obj, obj_id, export_format):
        """ export objects from api
        """
        self.__valide_export_format(export_format)
        res = self.zapi.configuration.export(options={export_obj: [obj_id]},
                                             format=export_format)
        return res

    def api_import(self, import_format, import_rules, import_source):
        """ import objects to zabbix
        """
        self.__valide_import_format(import_format)
        args = {
            'rules': import_rules,
            'format': import_format,
            'source': import_source
        }
        res = self.zapi.do_request('configuration.import', args)
        return res
    zapi = ZabbixAPI(url=zabbix['url'], user=zabbix['username'], password=zabbix['password'])
    print ('Auth Ok!')
except Exception as err:
    print('Erro ao conectar ao Zabbix')
    print('Erro: {}'.format(err))


hostgroup = 'SICI'


getHostGroup = zapi.do_request('hostgroup.get',
                            {
                                "output": "extend",
                                "filter": {
                                    "name": [
                                        hostgroup
                                    ],
                                "sortfield": ["name"],
                                "sortorder": "DESC"
                                }
                            }
                        )


getHost = zapi.do_request('host.get',
                            {
                                "output": "extend",
                                "selectGroups": "extend",
                                "groupids": getHostGroup['result'][0]["groupid"]
                            }
                        )
Exemple #16
0
    zapi = ZabbixAPI(url=zabbix['url'], user=zabbix['username'], password=zabbix['password'])
    print ('Auth Ok!')
except Exception as err:
    print('Erro ao conectar ao Zabbix')
    print('Erro: {}'.format(err))


hostgroup = 'SICI'


getHostGroup = zapi.do_request('hostgroup.get',
                            {
                                "output": "extend",
                                "filter": {
                                    "name": [
                                        hostgroup
                                    ],
                                "sortfield": ["name"],
                                "sortorder": "DESC"
                                }
                            }
                        )


print(getHostGroup)
#apiVersion = zapi.do_request('apiinfo.version')


request = zapi.do_request('event.get',
                            {
                                "output": "extend",
                                "select_acknowledges": "extend",
Exemple #17
0
# graph settings of screen row
screen_row_settings = [{"graph": {"width": 450, "height": 100}},
                       {"graph": {"width": 450, "height": 100}},
                       {"graph": {"width": 500, "height": 100}}
                       ]
# check settings and exit
if(col_number>len(screen_row_settings)):
    print("Your col_number value is: {}\nYour screen_row_settings length is: {}\n".format(col_number,len(screen_row_settings)))
    print("Increase number of lines in screen_row_settings list or decrease col_number value.")
    exit(1)
# init zabbix api connection
zapi = ZabbixAPI(url=server, user=zbx_user, password=zbx_pass)
# create host search params
params = {'filter': {'name': host_name}, 'output': 'extend'}
# searching for host
res = zapi.do_request('host.get',params)
# get host id
hostid = res['result'][0]['hostid']
# create zabbix graphs search params
params = {}
# set hostid
params['hostids'] = hostid
# set param for extended output
params['output'] = 'extend'
# set graph name search criteria
params['search'] = {'name': 'CAM STATS'}
# searching for graphs
res = zapi.do_request('graph.get',params)
# close zabbix server session
zapi.user.logout()
# create empty list of graph names