def CheckConnection(): try: zapi = ZabbixAPI(server=server, path="", log_level=loglevel) zapi.login(username, password) except: print bold + "\nCould'n connect to zabbix. Please check if URL " + server + " is avaiable" + reset exit(1)
def CheckConnection(): try: zapi = ZabbixAPI(server=server, path="", log_level=loglevel) zapi.login (username,password) except: print bold+"\nCould'n connect to zabbix. Please check if URL " + server + " is avaiable"+reset exit(1)
def zabbixhostsearch(self, ip): zapi = ZabbixAPI(server=server, path="", log_level=loglevel) zapi.login (username,password) hostids=zapi.host.get({"output":"extend", 'filter':{'ip':ip}}) if len(hostids) == 1: return hostids[0]['hostid'] else: print bold +"\nNothing founded. Please make sure you specified a correct IP \n"+reset
def getlist(self, type): zapi = ZabbixAPI(server=server, path="", log_level=loglevel) zapi.login (username,password) pattern='*' output='extend' if type == 'host': ids = zapi.host.get({"output":output, 'search':{'groupids':pattern}}) elif type == 'group': ids = zapi.hostgroup.get({"output":output, 'search':{"hostids":pattern}}) elif type == 'template': ids = zapi.template.get({'output':output, "search":{"hostid":pattern}}) return ids
def makehash(): return collections.defaultdict( makehash ) def check_status( freep ): #print WARNING if free % less than 10 if freep <= 10 and freep >=5: return "WARNING" elif freep <= 5: # print CRITICAL if % less than 5 return "CRITICAL" return "OK" # Connect to Zabbix server z=ZabbixAPI(server=zabbix_url) z.login(user=username, password=password) # Get hosts in the hostgroup get_hostgroup = z.hostgroup.get( { 'filter' : { 'name': hostgroup }, 'sortfield': 'name', 'select_hosts':'extend' }) get_hosts = z.host.get( { 'groupids': get_hostgroup[0]['groupid'], 'output': "extend" })
parser.add_argument('-d', '--dns', help='DNS') parser.add_argument('-i', '--ip', help='ip address') parser.add_argument('-p', '--port', help='port zabbix agent is listening on') parser.add_argument('-u', '--useip', help='1 or 0. connect to host by IP(1) | DNS(0)') parser.add_argument('-g', '--groups', help='comma-separated groups id or names') parser.add_argument('-t', '--templates', help='comma-separated template ids or names') parser.add_argument('-m','--macros', help='Macroses list. For example: macro1=value1,...,macroN=valueN') #help = 'Actually creating host. Macro are optional parameters', nargs='?') args = parser.parse_args() if len(sys.argv)<2: parser.parse_args(['-h']) #print bold+'\nExample: ./zabbix_host_add.py hostname:test dns:hostname.com ip:10.0.0.1 port:10050 useip:1 groups:10011,Linux,"test servers" templates:10026,10027,"new template" macros:macro1=value1,newmacro=newvalue'+reset zapi = ZabbixAPI(server=server, path="", log_level=loglevel) zapi.login(username,password) zmeth=ZabbixMethods() list = False if args.listhosts: print 'Current log level is',str(loglevel)+',','you may increase it' ids = zmeth.getlist('host') ids = [ x['host'] for x in ids ] list = True elif args.listgroups: ids = zmeth.getlist('group') ids = [ x['name'] for x in ids ] list = True elif args.listtemplates:
def trigger_list(self, server, username, password, listtype): zapi = ZabbixAPI(server=server, path="", log_level=0) zapi.login(username, password) triggerlist = zapi.trigger.get({ 'active': True, 'monitored': True, 'sortfield': 'priority', 'sortorder': 'DESC', #'sortfield': 'lastchange', 'filter': { 'value': 1 }, 'expandData': '1', #'expandDescription': '1', 'output': 'extend', 'skipDependent': False }) resulttext = u'' if listtype == '1': nm = 0 for x in triggerlist: ##################### Full data example # print x if x['priority'] == '0': message = u'NOT CLASSIFIED' nm = nm + 1 elif x['priority'] == '1': message = u'INFORMATIONAL' nm = nm + 1 elif x['priority'] == '2': message = u'WARNING' nm = nm + 1 elif x['priority'] == '3': message = u'AVERAGE' nm = nm + 1 elif x['priority'] == '4': message = u'HIGH' nm = nm + 1 elif x['priority'] == '5': message = u'DISASTER' nm = nm + 1 ################ Internal information ################ priority 0 - not classified, 1 -informational, 2 - warning, 3 - Average, 4 - High, 5 - Disaster resulttext = resulttext + u'\n' + message + u'::::' + x[ 'hostname'] + u'::::' + x['description'] ################ Code for Debug # print u'Resulttext1' + resulttext # print nm # print "__________________________________________________" # print len(hashmassive) # print hashmassive[2] # print "__________________________________________________" # return str(nm) return resulttext elif listtype == '2': hashmassive = [] nc = 0 inf = 0 warn = 0 avg = 0 high = 0 dis = 0 for x in triggerlist: hashmassive.append(x['triggerid']) if x['priority'] == '0': message = u'NOT CLASSIFIED' nc = nc + 1 elif x['priority'] == '1': message = u'INFORMATIONAL' inf = inf + 1 elif x['priority'] == '2': message = u'WARNING' warn = warn + 1 elif x['priority'] == '3': message = u'AVERAGE' avg = avg + 1 elif x['priority'] == '4': message = u'HIGH' high = high + 1 elif x['priority'] == '5': message = u'DISASTER' dis = dis + 1 #priority 0 - not classified, 1 -informational, 2 - warning, 3 - Average, 4 - High, 5 - Disaster resulttext = u'' if nc > 0: resulttext = str(resulttext) + u'NOT CLASSIFIED:' + str( nc) + u' ' else: print u'NOT CLASSIFIED:' + str(nc) if inf > 0: resulttext = str(resulttext) + u'INFORMATIONAL:' + str( inf) + u' ' else: print u'INFORMATIONAL:' + str(inf) if warn > 0: resulttext = str(resulttext) + u'WARNING:' + str(warn) + u' ' else: print u'WARNING:' + str(warn) if avg > 0: resulttext = str(resulttext) + u'AVERAGE:' + str(avg) + u' ' else: print u'AVERAGE:' + str(avg) if high > 0: resulttext = str(resulttext) + u'HIGH:' + str(high) + u' ' pass else: print u'HIGH:' + str(high) if dis > 0: resulttext = str(resulttext) + u'DISASTER:' + str(dis) else: print u'DISASTER:' + str(dis) ###### Old code # resulttext = u'NOT CLASSIFIED:' + str(nc) + u' ' + u'INFORMATIONAL:' + str(inf) + u' ' + u'WARNING:' + str(warn) + u' ' + u'AVERAGE:' + str(avg) + u' ' + u'HIGH:' + str(high) + u' ' + u'DISASTER:' + str(dis) # errcount = nc + inf + warn + avg + high + dis # return (resulttext, errcount) return (resulttext, hashmassive)
def main(): module = AnsibleModule(argument_spec=dict( username=dict(required=True), password=dict(required=True, no_log=True), hostname=dict(required=True), proto=dict(default="http", choices=["http", "https"]), validate_certs=dict(default=True, type="bool"), timeout=dict(default=120, type="int"), object=dict(required=True), action=dict(required=True, choices=["get", "set"]), params=dict(default={}, type="dict"), filter=dict(default={}, type="dict"), )) try: zapi = ZabbixAPI("{}://{}/zabbix".format(module.params["proto"], module.params["hostname"]), validate_certs=module.params["validate_certs"], timeout=module.params["timeout"]) zapi.login(module.params["username"], module.params["password"]) conf_object = getattr(zapi, module.params["object"]) msg = [] # Firt handle objcects witout 'get' method # 'configuration' if module.params["object"] == "configuration": temp_ids = get_templateid_by_name( zapi, module.params['params']['source']) if len(temp_ids) > 0: result = "Template already exists in Zabbix config" module.exit_json(changed=False, result=result, msg=msg) return method = getattr(conf_object, "import") result = method(module.params['params']) msg.append(module.params['params']) module.exit_json(changed=True, result=result, msg=msg) return # passed params become filter if latter is not specified # we need to find a desired object somehow if module.params["filter"] == {}: query_filter = module.params["params"] else: query_filter = module.params["filter"] method = getattr(conf_object, "get") params = {} params["output"] = "extend" # add additional options for actions: if module.params["object"] == 'action': params.update({ "selectOperations": "extend", "selectRecoveryOperations": "extend", "selectFilter": "extend", }) params["filter"] = query_filter result = method(params) # if 'get' was specified exit right here if module.params["action"] == "get": module.exit_json(changed=False, result=result, msg=msg) return # 'set' was specified # 'mediatype', 'hostgroup' and 'action' # not all methods for hostgroup are supported if module.params["object"] not in ["action", "mediatype", "hostgroup"]: msg = ("Unable to operate with object '{}'").format( module.params["object"]) module.fail_json(msg=msg) return # No objects found. Need to create objects if len(result) == 0: method = getattr(conf_object, "create") result = method(module.params['params']) module.exit_json(changed=True, result=result, msg=msg) return # One or more objects exist. Need to update them. method = getattr(conf_object, "update") # If more than 1 object found makes sense to warn user warnings = None if len(result) > 1: warnings = "Filter '{}' matches several items".format(query_filter) # Loop over found object if they match desired config need_to_change = False for elem in result: for k, v in module.params['params'].items(): if k in elem and elem[k] == v: continue need_to_change = True return_obj = {"changed": False, "result": result, "msg": msg} if warnings is not None: return_obj["warnings"] = warnings # Nothing should be changed. Return. if not need_to_change: module.exit_json(**return_obj) return # Now we need to update objects # copy result to data and update fields from module.params['params'] data = [] for elem in result: obj_ids = {k: v for k, v in elem.items() if k.endswith("id")} obj_ids.update(module.params['params']) data.append(obj_ids) result = method(data) return_obj["changed"] = True return_obj["result"] = data module.exit_json(**return_obj) return except ZabbixAPIException as e: module.fail_json(msg="Zabbix API exception:{}".format(e)) return
def trigger_list(self, server, username, password, listtype): zapi = ZabbixAPI(server=server, path="", log_level=0) zapi.login(username, password) triggerlist = zapi.trigger.get( {'active' : True, 'monitored': True, 'sortfield': 'priority', 'sortorder' : 'DESC', #'sortfield': 'lastchange', 'filter': {'value': 1}, 'expandData': '1', #'expandDescription': '1', 'output': 'extend', 'skipDependent': False}) resulttext = u'' if listtype == '1' : nm = 0 for x in triggerlist : ##################### Full data example # print x if x['priority'] == '0' : message = u'NOT CLASSIFIED' nm = nm + 1 elif x['priority'] == '1' : message = u'INFORMATIONAL' nm = nm + 1 elif x['priority'] == '2' : message = u'WARNING' nm = nm + 1 elif x['priority'] == '3' : message = u'AVERAGE' nm = nm + 1 elif x['priority'] == '4' : message = u'HIGH' nm = nm + 1 elif x['priority'] == '5' : message = u'DISASTER' nm = nm + 1 ################ Internal information ################ priority 0 - not classified, 1 -informational, 2 - warning, 3 - Average, 4 - High, 5 - Disaster resulttext = resulttext + u'\n' + message + u'::::' + x['hostname'] + u'::::' + x['description'] ################ Code for Debug # print u'Resulttext1' + resulttext # print nm # print "__________________________________________________" # print len(hashmassive) # print hashmassive[2] # print "__________________________________________________" # return str(nm) return resulttext elif listtype == '2' : hashmassive = [] nc = 0 inf = 0 warn = 0 avg = 0 high = 0 dis = 0 for x in triggerlist : hashmassive.append(x['triggerid']) if x['priority'] == '0' : message = u'NOT CLASSIFIED' nc = nc + 1 elif x['priority'] == '1' : message = u'INFORMATIONAL' inf = inf + 1 elif x['priority'] == '2' : message = u'WARNING' warn = warn + 1 elif x['priority'] == '3' : message = u'AVERAGE' avg = avg + 1 elif x['priority'] == '4' : message = u'HIGH' high = high + 1 elif x['priority'] == '5' : message = u'DISASTER' dis = dis + 1 #priority 0 - not classified, 1 -informational, 2 - warning, 3 - Average, 4 - High, 5 - Disaster resulttext = u'' if nc > 0 : resulttext = str(resulttext) + u'NOT CLASSIFIED:' + str(nc) + u' ' else : print u'NOT CLASSIFIED:' + str(nc) if inf > 0 : resulttext = str(resulttext) + u'INFORMATIONAL:' + str(inf) + u' ' else : print u'INFORMATIONAL:' + str(inf) if warn > 0 : resulttext = str(resulttext) + u'WARNING:' + str(warn) + u' ' else : print u'WARNING:' + str(warn) if avg > 0 : resulttext = str(resulttext) + u'AVERAGE:' + str(avg) + u' ' else : print u'AVERAGE:' + str(avg) if high > 0 : resulttext = str(resulttext) + u'HIGH:' + str(high) + u' ' pass else : print u'HIGH:' + str(high) if dis > 0 : resulttext = str(resulttext) + u'DISASTER:' + str(dis) else : print u'DISASTER:' + str(dis) ###### Old code # resulttext = u'NOT CLASSIFIED:' + str(nc) + u' ' + u'INFORMATIONAL:' + str(inf) + u' ' + u'WARNING:' + str(warn) + u' ' + u'AVERAGE:' + str(avg) + u' ' + u'HIGH:' + str(high) + u' ' + u'DISASTER:' + str(dis) # errcount = nc + inf + warn + avg + high + dis # return (resulttext, errcount) return (resulttext, hashmassive)