Ejemplo n.º 1
0
def zbx_host_config(zapi, hosts):
    ''' return a list of hosts :
        - attributes : as values of dict
        - macros, groups, templates, inventory, tags(*) : as list of dict
        
        * tags only with zabbix > 4.2.0
    '''

    result = []
    host = []
    global sel
    global desc

    convert = zbx_table("init")

    # query the proxy dictionnary
    proxy_name = zbx_proxy_name(zapi)

    idx_host = 0


    for ho in hosts:
        idx_host += 1    

        if v_zabbix >=420:
            host = zapi.do_request('host.get',
                    {"output": sel["hosts"],
                    "hostids": ho["hostid"],
                    "selectMacros": sel["macros"],
                    "selectGroups": sel["groups"],
                    "selectParentTemplates": sel["templates"],
                    "selectInventory": sel["inventory"],
                    # "selectItems" : sel["items"],
                    "selectTags": sel["tags"],
                    })['result'][0]
        else:
            host = zapi.do_request('host.get',
                    {"output": sel["hosts"],
                    "hostids": ho["hostid"],
                    "selectMacros": sel["macros"],
                    "selectGroups": sel["groups"],
                    "selectParentTemplates": sel["templates"],
                    "selectInventory": sel["inventory"],
                    # "selectItems" : sel["items"],
                    })['result'][0]
        # print(host[0]["host"])


        logging.info("host (" + str(idx_host) + "/"  + str(len(hosts)) + ") : " + host["host"])

        fmt_host = zbx_fmt_host(zapi, host, convert, proxy_name)

        result.append(fmt_host)

        if (limit_host != 0 and idx_host >= limit_host):
            logging.info("ended program due to host scan number limitation (--limit parameter)")
            break

    return result
Ejemplo n.º 2
0
def save_inhg(zapi, te, fn1, fn2):
    hostgroups = zapi.hostgroup.get(output="extend", hostids=te["templateid"])
    for hg in hostgroups:
        if grpmask.search(hg["name"]):
            fdir = dir_data + hg["name"] + "/doc/"
            to_file = fdir + fn2
            result = copy_file(fdir, fn1, to_file, "doc")
            logging.info("doc '%s.html' %s in '%s' group", te["name"], result, hg["name"])
        else:
            result = "nomatch"
            logging.info("doc '%s.html' %s in '%s' group", te["name"], result, hg["name"])
    return result
Ejemplo n.º 3
0
def zbx_stat(df, ws, val, pv_lst, startcol):
    ''' store pivot statistics in specific worksheet
        inputs :
            df : dataframe
            ws : worksheet
            val : count value for pivot
            pv_list : list of columns pivot compute
            statcol : starting column for value writing (the row is allways set to 1) 
    '''
    for pv in pv_lst:
        pivot = df.pivot_table(index=pv, values=val, aggfunc="count")
        if mode_verbose:
            logging.info("stat process -> %s statistics", pv)
        xl_stat(ws, pivot, startcol)
        startcol += 3

    return
Ejemplo n.º 4
0
def export_tpl(zapi, te):
    ''' format export template output


    '''
    result = ""

    # generate xml file 
    xml_formated = zbx_exportXML(zapi, te)

    with open(tmp_xml, mode='w') as export_file:
        export_file.write(xml_formated)

    # generate json file
    json_formated = zbx_exportJSON(zapi, te)
    with open(tmp_json, mode='w') as export_file:
        export_file.write(json_formated)

    # save file
    hostgroups = zapi.hostgroup.get(output="extend", hostids=te["templateid"])
    for hg in hostgroups:
        if grpmask.search(hg["name"]):
            fdir = dir_data + hg["name"] + "/"
            fn2 = fdir + te["name"] + ".xml"
            fn3 = fdir + te["name"] + ".json"            
            result = copy_file(fdir, tmp_xml, fn2, "xml")
            logging.info("template '%s.xml' %s in '%s' group", te["name"], result, hg["name"])
            result = copy_file(fdir, tmp_json, fn3, "json")
            logging.info("template '%s.json' %s in '%s' group", te["name"], result, hg["name"])
        else:
            result = "nomatch"
            logging.info("template '%s' %s in '%s' group", te["name"], result, hg["name"])    


    return result
Ejemplo n.º 5
0
        1/ args parameter
        2/ config parameters
        3/ if config parameter not exist then args is the default
    '''

    module = __file__[__file__.find("/") + 1:__file__.find(".")]
    mod_path = os.path.dirname(os.path.abspath(__file__))
    args = parse_arg()
    conf_file = mod_path + "/" + args.config
    config = parse_config(conf_file, module)

    mode_verbose = args.verbose or config.getboolean("default",
                                                     "mode_verbose") or False
    init_log(config, mode_verbose)

    logging.info("program started")

    limit = args.limit or 0
    infile = args.xlfile or config[module]["infile"]

    xlfile = args.xlfile or config[module]["xlfile"] or "host.xlsx"

    zbxtool_dir = config["paths"]["zbxtool_dir"]
    dir_data = zbxtool_dir + "/" + config[module]["save_dir"] + "/"
    outfile = dir_data + xlfile

    logging.info("output file is : %s", outfile)

    if not os.path.exists(dir_data):
        os.makedirs(dir_data)
Ejemplo n.º 6
0
    args = parse_arg()
    conf_file = mod_path + "/" + args.config
    config = parse_config(conf_file,module)

    mode_verbose = args.verbose or config.getboolean("default", "mode_verbose") or False
    init_log(config, mode_verbose)

    zbxenv = args.zbxenv or config["default"]["env"] or "Zabbix"
    limit_host = args.limit or 0

    xlfile = args.xlfile or config[module]["xlfile"] or "host.xlsx"

    zbxtool_dir = config["paths"]["zbxtool_dir"]  
    dir_data = zbxtool_dir + "/"  + config[module]["save_dir"] + "/"  + zbxenv + "/"

    logging.info("save directory is : %s", dir_data)

    if not os.path.exists(dir_data):
        os.makedirs(dir_data)

    if limit_host != 0:
        logging.info("max number of host activated %s hosts", str(limit_host))

    
    logging.info("zabbix environment = %s ", zbxenv)


    # init global variable
    global sel
    sel = {}
    global desc
Ejemplo n.º 7
0
def zbx_tpl_qry(zapi, te, qry):
    ''' return a list containing the list of user macro
          - zapi : zabbix context
          - te : template id
          - qry : qry name (macros, items, triggers, drules ...))
          - sel : specified columns
          - desc : table title
          result_fmt = {title: [], data: []}
          * the values of specific list of reserved word are returned with "** not shown **"
    '''
    result = {}
    zbx_resp = ""
    global sel
    global desc

    if mode_verbose:
        logging.info("query template ID = %s / QRY = %s", te, qry)

    #  print("QRY : ", qry, "\nSEL:", sel, "\nDESC:", desc)
    title = dict(zip(sel[qry], desc[qry]))
    convert = zbx_table("init")
    notshown = zbx_table(qry)  

    if qry == "template":
        zbx_resp = zapi.do_request('template.get',{"output": sel[qry],
                             "templateids": te})['result']
    elif qry == "hostgroup":
        zbx_resp = zapi.do_request('hostgroup.get',{"output": sel[qry],
                             "hostids": te})['result']
    elif qry == "macros":
        zbx_resp = zapi.do_request('usermacro.get',{"output": sel[qry],
                             "hostids": te})['result']
    elif qry == "items":
        zbx_resp = zapi.do_request('item.get',{"output": sel[qry],   
                        "hostids": te})['result']
    elif qry == "drule_items":
        zbx_resp = zapi.do_request('itemprototype.get',{"output": sel[qry],   
                        "discoveryids": te})['result']
    elif qry == "drule_triggers":
        zbx_resp = zapi.do_request('triggerprototype.get',{"output": sel[qry],   
                        "discoveryids": te,
                        "expandExpression": True,
                        "selectTags":"extend",
                        })['result']
    elif qry == "triggers":
        zbx_resp = zapi.do_request('trigger.get',
                        {"output": sel[qry],
                        "hostids": te,
                        "expandExpression": True,
                        "selectTags":"extend",
                        })['result']
    elif qry == "webscenar":
        result=[]
        lst_webscenar = zapi.do_request('httptest.get',
                        {"output": sel[qry],
                        "hostids": te,
                        "selectSteps": "extend",
                        "expandName": True,
                        "expandStepName": True
                        })['result']
        # print(lst_webscenar)
        for webscenar in lst_webscenar:
            res_webscenar = {}
            res_webscenar.update({"scenar": zbx_tpl_fmtquery([webscenar],qry,sel[qry], title,convert,notshown)})
            tit_webstep = dict(zip(sel["webstep"], desc["webstep"]))
            res_webscenar.update({"step": zbx_tpl_fmtquery(webscenar["steps"],qry,sel["webstep"], tit_webstep,convert,notshown)})
       
            result.append(res_webscenar)

        # print(result)
        return result

    elif qry == "drules":
        result = []
        lst_drules = zapi.do_request('discoveryrule.get',
                        {"output": "itemid",
                        "hostids": te,
                        })['result']
         # print("drules trouvees:", lst_drules)
        for drule in lst_drules:
            res_drule = {}
            zbx_drules = zapi.do_request('discoveryrule.get',
                             {"output": sel["drules"],
                             "itemids": drule["itemid"],
                             })['result']
            res_drule.update({"drule": zbx_tpl_fmtquery(zbx_drules, qry, sel[qry], title, convert, notshown)})
            res_drule.update({"items": zbx_tpl_qry(zapi, drule["itemid"], "drule_items")})
            res_drule.update({"triggers": zbx_tpl_qry(zapi, drule["itemid"], "drule_triggers")})
            result.append(res_drule)
              # print(result)
        return result

    elif qry == "graphs":
        result = []
        # lst_graphs = zapi.do_request('graph.get',
        #                  {"output": "itemid",
        #                  "hostids": te,
        #                  })['result']

    result=zbx_tpl_fmtquery(zbx_resp, qry, sel[qry], title, convert, notshown) 
       
    return result
Ejemplo n.º 8
0
        2/ config parameters
        3/ if config parameter not exist then args is the default
    '''

    module = __file__[__file__.find("/")+1:__file__.find(".")]
    mod_path = os.path.dirname(os.path.abspath(__file__))
    args = parse_arg()
    conf_file = mod_path + "/" + args.config
    config = parse_config(conf_file,module)

    mode_verbose = args.verbose or config.getboolean("default", "mode_verbose") or False
    init_log(config, mode_verbose)

    tplmask_name = args.tplname or config[module]["tplname"] or "Template"
    if mode_verbose:
        logging.info("template name mask = " + tplmask_name)

    grpmask_name = args.grpname or config[module]["grpname"] or "Template"
    grpmask = re.compile(grpmask_name)
    if mode_verbose:
        logging.info("group template name mask = " + grpmask_name)

    zbxenv = args.zbxenv or config["default"]["env"] or "Zabbix"
    if mode_verbose:
        logging.info("environnement zabbix = " + zbxenv)


    # init global variable
    global sel
    sel = {}
    global desc