def main(): """The main function""" login = "******"#raw_input("Login: "******"1kassiope@"#raw_input("Password: "******"Connected to Zabbix API Version %s" % zapi.api_version() template_id = zapi.template.get({"output": "extend", "search": {"name": 'App RabbitMQ'}})[0]["templateid"] print "Template ID", template_id hosts = [] items = {} gitems = {} print "Host IDs:" for rig in zapi.host.get({"templateids":template_id}): hosts.append(rig["hostid"]) print rig["hostid"], rig["name"] print "Collecting items and assigning colors to them..." for i in hosts: items[i] = zapi.item.get({"hostids": i, "search": {"key_": 'queue_message_stats'}}) gitems[i] = [] for j in items[i]: gitems[i].append({"itemid": j["itemid"], "color": '%02X%02X%02X' % (rand(), rand(), rand())}) print "Creating graph for", i try: zapi.graph.create({"name": "Aggregated queue stats", "width": 900, "height": 300, "gitems": gitems[i]}) except: print "Graph already exists or cannot be created" continue print "All done"
def main(): global zapi, hostid zapi = ZabbixAPI(server=server, path="", log_level=6) zapi.login(username, password) hostid = zapi.host.get({"filter":{"host":hostname}})[0]["hostid"] #print hostid add_counters(hrl)
def get_metric(self, host, item, **kwargs): """ Returns the last value of "item" from "host" :param host: hostname of itemholder :param item: itemname of wanted item :param kwargs: Optional parameter :return: """ if self.__address is not None: if 'password' in kwargs: password = kwargs['password'] else: password = '******' if 'username' in kwargs: username = kwargs['username'] else: username = '******' zapi = ZabbixAPI(server='http://'+self.__address+'/zabbix', path="", log_level=0) zapi.login(username, password) hostid = zapi.host.get({"filter": {"host": host}})[0]["hostid"] item_values = zapi.item.get({"params": {"hostids": hostid}, "filter": {"name": item, "hostid": hostid}}) return item_values[0]["lastvalue"] else: return None
class zabbix: def __init__(self,server=None,log_level=0,log=None): """ Accepts keyword args for Server and log_level @type server: str @param server: Zabbix Server URL @type log_level: int @param log_level: Logging level for this class """ self.zapi = ZabbixAPI(server=server,log_level=log_level) if log == None: self._log = setup_logging() else: self._log = log def login(self,username=None,password=None): """ Login handler """ try: self._log.debug("Attempting to login") self.zapi.login(username,password) self._log.debug("Login successfull") except Exception, e: # Unable to login, lets just bomb out self._log.error("Failed to login - exiting") sys.exit()
def main(): module = AnsibleModule( argument_spec=dict( server_url=dict(type='str', required=True, aliases=['url']), login_user=dict(type='str', required=True), login_password=dict(type='str', required=True, no_log=True), http_login_user=dict(type='str',required=False, default=None), http_login_password=dict(type='str',required=False, default=None, no_log=True), host_groups=dict(type='list', required=True, aliases=['host_group']), state=dict(default="present", choices=['present','absent']), timeout=dict(type='int', default=10) ), supports_check_mode=True ) if not HAS_ZABBIX_API: module.fail_json(msg="Missing requried zabbix-api module (check docs or install with: pip install zabbix-api)") server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] host_groups = module.params['host_groups'] state = module.params['state'] timeout = module.params['timeout'] zbx = None # login to zabbix try: zbx = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password) zbx.login(login_user, login_password) except Exception, e: module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)
def __init__(self): self.defaultgroup = 'group_all' self.zabbix_server = None self.zabbix_username = None self.zabbix_password = None self.read_settings() self.read_cli() if self.zabbix_server and self.zabbix_username: try: api = ZabbixAPI(server=self.zabbix_server) api.login(user=self.zabbix_username, password=self.zabbix_password) except BaseException, e: print "Error: Could not login to Zabbix server. Check your zabbix.ini." sys.exit(1) if self.options.host: data = self.get_host(api, self.options.host) print json.dumps(data, indent=2) elif self.options.list: data = self.get_list(api) print json.dumps(data, indent=2) else: print "usage: --list ..OR.. --host <hostname>" sys.exit(1)
def __init__(self): self.defaultgroup = 'group_all' self.zabbix_server = None self.zabbix_username = None self.zabbix_password = None self.read_settings() self.read_cli() if self.zabbix_server and self.zabbix_username: try: api = ZabbixAPI(server=self.zabbix_server) api.login(user=self.zabbix_username, password=self.zabbix_password) except BaseException as e: print("Error: Could not login to Zabbix server. Check your zabbix.ini.", file=sys.stderr) sys.exit(1) if self.options.host: data = self.get_host(api, self.options.host) print(json.dumps(data, indent=2)) elif self.options.list: data = self.get_list(api) print(json.dumps(data, indent=2)) else: print("usage: --list ..OR.. --host <hostname>", file=sys.stderr) sys.exit(1) else: print("Error: Configuration of server and credentials are required. See zabbix.ini.", file=sys.stderr) sys.exit(1)
def LoginZabbixServer(server, username, password): try: zapi = ZabbixAPI(server=server, path="", log_level=6) zapi.login(username, password) except ZabbixAPIException, e: print e return False, None
def api_connect(): """Connect to Zabbix API""" try: zapi = ZabbixAPI(server=ZABBIX['url']) zapi.login(ZABBIX['user'], ZABBIX['pass']) except Exception,e: logger.error("Can't login to zabbix server: %s" %(e)) raise ZabbixAlarms, "Can't login to zabbix server: %s" %(e)
def printHostList() : zapi = ZabbixAPI(server=server) zapi.login(settings['zabbixusername'], settings['zabbixpassword']) result = zapi.host.get({"output": "extend"}) hostlist = [] for i in result : print i["name"]
class ICNaaSMonitor(object): def __init__(self, maas_endpoint): """ Initialize the ICNaaS Monitor object """ # Connect to MaaS if maas_endpoint is None: self.maas_endpoint = '130.92.70.142' else: self.maas_endpoint = maas_endpoint self.server = 'http://' + self.maas_endpoint + '/zabbix' self.username = MAAS_UID self.password = MAAS_PWD self.connFailed = False # Zabbix API self.zapi = ZabbixAPI(server=self.server) for i in range(1,4): try: print('*** Connecting to MaaS at ' + self.server) self.zapi.login(self.username, self.password) print('*** Connected to MaaS') self.connFailed = False break except Exception as e: print('*** Caught exception: %s: %s' % (e.__class__, e)) traceback.print_exc() print('*** Connection to MaaS has failed! Retrying ('+str(i)+').') self.connFailed = True time.sleep(3) if self.connFailed: print('*** Connection to MaaS has failed! Waiting for an update to try again.') self.__metrics = [] @property def metrics(self): return self.__metrics @metrics.setter def metrics(self, value): self.__metrics = value pass def get(self, public_ip): measured_values = {} for metric in self.metrics: measured_values[metric] = self.get_value(metric, public_ip) if measured_values[metric] is None: return return measured_values def get_value(self, metric, public_ip): raise NotImplementedError
def create_hgroup() : global str_res try: zapi = ZabbixAPI(settings["zabbixurl"]) zapi.login(settings["zabbixusername"],settings["zabbixpassword"]) var = list_instances.list_instances() # list of dictionaries (name, id, vm) except Exception, error: print "Error connecting to Zabbix" raise error
def delHostZabbix(ip): # login to zabbix server zapi = ZabbixAPI(server=ZAB_CONF['server'], path="", log_level=6) zapi.login(ZAB_CONF['username'], ZAB_CONF['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 result=zapi.host.delete({"hostid":hostids})
def zabbixHostDelete(hostIdList): """ To delete the host in the zabbix server hostIdList - The zabbix host id """ try: zapi = ZabbixAPI(server = settings.ZABBIX_SERVER) zapi.login(settings.ZABBIX_USERNAME, settings.ZABBIX_PASSWORD) result = zapi.host.delete(hostIdList) return True except Exception, e: debugException(e)
def zabbixHostCreate(params): """ To create the host in the zabbix server Args: { params - parameter dictionary } """ #Setting the zabbix details zapi = ZabbixAPI(server = settings.ZABBIX_SERVER) zapi.login(settings.ZABBIX_USERNAME, settings.ZABBIX_PASSWORD) returnHost = zapi.host.create(params) return returnHost
class DataRetriever(): server = "http://127.0.1.1/zabbix" username = "******" password = "******" hist_type = 3 dens = 1 time_format = "%d-%m-%Y %H:%M:%S" def __init__(self, item_key): self.zapi = ZabbixAPI(server=self.server, path="", log_level=3) self.zapi.login(self.username, self.password) self.item_key = item_key def set_config(self, config): self.hist_type = config.get("general", "hist_type") self.dens = int(config.get("general", "dens")) # Time format: "%d-%m-%Y %H:%M:%s" def get_data(self, str_time_from, str_time_to): time_from = int(time.mktime(time.strptime(str_time_from, self.time_format))) time_to = int(time.mktime(time.strptime(str_time_to, self.time_format))) print str_time_from, time_from print str_time_to, time_to hostid = self.zapi.host.get({"output":"extend", "filter": {"host":"localhost"}})[0]["hostid"] itemid = self.zapi.item.get({"output" : "extend", "hostids" : [hostid], "filter" : {"key_" : self.item_key}})[0]['itemid'] H = self.zapi.history.get({"time_from" : str(time_from), "time_till" : str(time_to), "output":"extend", "itemids" : [itemid], "hostids" : [hostid], "history" : self.hist_type}) result = [[], []] i = 0 for el in H: i += 1 if i % self.dens == 0: result[0].append(int(el["clock"]) - time_from) result[1].append(float(el["value"])) return result
def __init__(self, maas_endpoint): """ Initialize the ICNaaS Monitor object """ # Connect to MaaS if maas_endpoint is None: self.maas_endpoint = '130.92.70.142' else: self.maas_endpoint = maas_endpoint self.server = 'http://' + self.maas_endpoint + '/zabbix' self.username = MAAS_UID self.password = MAAS_PWD self.connFailed = False # Zabbix API self.zapi = ZabbixAPI(server=self.server) for i in range(1,4): try: print('*** Connecting to MaaS at ' + self.server) self.zapi.login(self.username, self.password) print('*** Connected to MaaS') self.connFailed = False break except Exception as e: print('*** Caught exception: %s: %s' % (e.__class__, e)) traceback.print_exc() print('*** Connection to MaaS has failed! Retrying ('+str(i)+').') self.connFailed = True time.sleep(3) if self.connFailed: print('*** Connection to MaaS has failed! Waiting for an update to try again.') self.__metrics = []
def __init__(self, region, access_key, secret, pref_if, zbx_url, zbx_user, zbx_pass, set_macro): self.region = region self.access_key = access_key self.secret = secret self.pref_if = pref_if self.zbx_url = zbx_url self.zbx_user = zbx_user self.zbx_pass = zbx_pass self.set_macro = set_macro self.ec2 = boto3.resource( 'ec2', region_name=region, aws_access_key_id=access_key, aws_secret_access_key=secret ) self.client = boto3.client( 'autoscaling', region_name=region, aws_access_key_id=access_key, aws_secret_access_key=secret ) self.zapi = ZabbixAPI(server=self.zbx_url) self.zapi.login(self.zbx_user, self.zbx_pass)
def __init__(self, maas_endpoint): """ Initialize the RCBaaS Monitor object """ # Connect to MaaS if maas_endpoint is None: self.maas_endpoint = '160.85.4.27' else: self.maas_endpoint = maas_endpoint self.server = 'http://' + self.maas_endpoint + '/zabbix' self.username = MAAS_UID self.password = MAAS_PWD self.connFailed = False self.metrics = [RCB_CPU, RCB_LOAD, RCB_TOTAL_MEMORY, RCB_AVAILABLE_MEMORY] # Zabbix API self.zapi = ZabbixAPI(server=self.server) for i in range(1,4): try: print('*** Connecting to MaaS') self.zapi.login(self.username, self.password) print('*** Connected to MaaS') self.connFailed = False except Exception as e: #print('*** Caught exception: %s: %s' % (e.__class__, e)) #traceback.print_exc() print('*** Connection to MaaS has failed! Retrying ('+str(i)+').') self.connFailed = True time.sleep(3) if self.connFailed: print('*** Connection to MaaS has failed! Waiting for an update to try again.') self.__metrics = []
class ImportCommand(Command): description = "import zabbix global scripts and global macros" user_options = [("frontend-url=", "f", "zabbix frontend url"), ("user="******"u", "zabbix user name"), ("password="******"p", "zabbix password")] def initialize_options(self): # set default value self.frontend_url = "http://localhost/zabbix" self.user = "******" self.password = "******" def finalize_options(self): pass def run(self): from zabbix_api import ZabbixAPI, ZabbixAPIException from xml.etree import ElementTree # connect zabbix frontend try: self.zabbix_api = ZabbixAPI(self.frontend_url) self.zabbix_api.login(self.user, self.password) except ZabbixAPIException, e: print "Failed to connect zabbix frontend: %s" % str(e[0]).partition("while sending")[0] return # import templates print "Import templates" try: with open(os.path.join(pwd, "misc/import_data/templates.xml")) as f: template_xml = f.read() req = self.zabbix_api.json_obj("configuration.import", { "format": "xml", "source": template_xml, "rules": { "items": {"createMissing": True}, "applications": {"createMissing": True}, "graphs": {"createMissing": True}, "groups": {"createMissing": True}, "templateLinkage": {"createMissing": True}, "templates": {"createMissing": True}, "triggers": {"createMissing": True}, } }) self.zabbix_api.do_request(req) except IOError, e: print " " + str(e)
def zbxLogin(self): self.zapi = ZabbixAPI(server=self.server, log_level=0) try: self.zapi.login(self.username, self.password) print "Zabbix API Version: %s" % self.zapi.api_version() print "Logged in: %s" % str(self.zapi.test_login()) except ZabbixAPIException, e: sys.stderr.write(str(e) + "\n")
def login(self): """Do API login""" try: self.api = ZabbixAPI(server=self.url) self.api.login(self.username, self.password) except Exception, e: raise zoopError("Unable to log in with provided credentials.") self.debug(logging.ERROR, "Unable to log in with provided credentials. Error %s" % e.args[0])
def main(): zapi = ZabbixAPI(server='http://zabbix-server01.dc.nova/zabbix') zapi.login(zabbix_user, zabbix_pwd) host_response = zapi.host.get({'groupids': [8,9], 'selectInterfaces': 'extend'}) hosts = [] for host in host_response: hosts.append({'nome': host['host'], 'ip': host['interfaces'][0]['ip'], 'host_id': int(host['hostid'])}) arquivo = os.path.dirname(os.path.realpath(__file__)) + '/servidores_zabbix.json' with open(arquivo, 'w') as arq: json.dump(hosts, arq)
class zoop: """Outermost class for all nested classes""" def __init__(self, url=None, username=None, password=None, logLevel=None, logfile=None): if not (url and username and password): raise zoopError("Valid url, username and password must be passed at instance creation.") else: self.logconfig(logLevel, logfile) self.url = url self.username = username self.password = password # Populate these values in these subclasses so they are filled. self.connect() def logconfig(self, logLevel, logfile): if logfile is None: log_hndlr = logging.StreamHandler(sys.stdout) else: try: log_hndlr = logging.FileHandler(logfile) except: log_hndlr = logging.StreamHandler(sys.stdout) self.logger = logging.getLogger("zoop.%s" % self.__class__.__name__) self.logger.addHandler(log_hndlr) if logLevel is None: logLevel = "WARNING" self.logger.setLevel(logLevel) def connect(self): """Do login and fill the inner class API values""" self.login() self.fillInnerClassesAPI() def login(self): """Do API login""" try: self.api = ZabbixAPI(server=self.url) self.api.login(self.username, self.password) except Exception, e: raise zoopError("Unable to log in with provided credentials.") self.debug(logging.ERROR, "Unable to log in with provided credentials. Error %s" % e.args[0])
class ZbxOperation: def __init__(self, url, username, password): self.api = ZabbixAPI(server=url) self.api.login(username, password) def get_trigger_id(self, host_name, trigger_name): result = self.api.trigger.get({ "filter": { "host": host_name, "name": trigger_name, }}) return result[0]['triggerid'] def delete_trigger_dependency(self, trigger_id): self.api.trigger.deletedependencies({"triggerid": trigger_id}) def add_trigger_dependency(self, trigger_id, depend_on_id): self.api.trigger.adddependencies({"triggerid": trigger_id, "dependsOnTriggerid": depend_on_id})
class BaseCreator(object): """ Base class for Zabbix creator """ def __init__(self, options): self.options = options self.server = "http://%s/api_jsonrpc.php " % self.options.server self.username = self.options.username self.password = self.options.password self.zbxLogin() def zbxLogin(self): self.zapi = ZabbixAPI(server=self.server, log_level=0) try: self.zapi.login(self.username, self.password) print "Zabbix API Version: %s" % self.zapi.api_version() print "Logged in: %s" % str(self.zapi.test_login()) except ZabbixAPIException, e: sys.stderr.write(str(e) + "\n")
def run(self): from zabbix_api import ZabbixAPI, ZabbixAPIException from xml.etree import ElementTree # connect zabbix frontend try: self.zabbix_api = ZabbixAPI(self.frontend_url) self.zabbix_api.login(self.user, self.password) except ZabbixAPIException, e: print "Failed to connect zabbix frontend: %s" % str(e[0]).partition("while sending")[0] return
def map_create(args): #Function creates value maps in Zabbix server via API result = False value_map = parse_mib(args.mib_file, args.value) if args.map_name: name = args.map_name else: name = args.value value_map_rq = { "name": name, "mappings": value_map } zbx_srv = ZabbixAPI(server = args.server) try: zbx_srv.login(user = args.user, password = args.password) print "Zabbix API Version: %s" % zbx_srv.api_version() print "Logged in: %s" % str(zbx_srv.test_login()) except ZabbixAPIException, e: sys.exit(error_parse(e))
def main(): module = AnsibleModule( argument_spec=dict( server_url=dict(type='str', required=True, aliases=['url']), login_user=dict(type='str', required=True), login_password=dict(type='str', required=True, no_log=True), hostgroup_name=dict(type='list', required=True), http_login_user=dict(type='str', required=False, default=None), http_login_password=dict(type='str', required=False, default=None, no_log=True), validate_certs=dict(type='bool', required=False, default=True), timeout=dict(type='int', default=10) ), supports_check_mode=True ) if module._name == 'zabbix_group_facts': module.deprecate("The 'zabbix_group_facts' module has been renamed to 'zabbix_group_info'", version='2.13') if not HAS_ZABBIX_API: module.fail_json(msg=missing_required_lib('zabbix-api', url='https://pypi.org/project/zabbix-api/'), exception=ZBX_IMP_ERR) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] validate_certs = module.params['validate_certs'] hostgroup_name = module.params['hostgroup_name'] timeout = module.params['timeout'] zbx = None # login to zabbix try: zbx = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password, validate_certs=validate_certs) zbx.login(login_user, login_password) atexit.register(zbx.logout) except Exception as e: module.fail_json(msg="Failed to connect to Zabbix server: %s" % e) host = Host(module, zbx) host_groups = host.get_group_ids_by_group_names(hostgroup_name) module.exit_json(host_groups=host_groups)
def login_zabbix(self): # set proxy information if required proxy = self.get_option('proxy') os.environ['http_proxy'] = proxy os.environ['HTTP_PROXY'] = proxy os.environ['https_proxy'] = proxy os.environ['HTTPS_PROXY'] = proxy server_url = self.get_option('server_url') http_login_user = self.get_option('login_user') http_login_password = self.get_option('login_password') validate_certs = self.get_option('validate_certs') timeout = self.get_option('timeout') self._zapi = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password, validate_certs=validate_certs) self.login() self._zbx_api_version = self._zapi.api_version()[:5]
def main(): module = AnsibleModule(argument_spec=dict( server_url=dict(type='str', required=True, aliases=['url']), login_user=dict(type='str', required=True), login_password=dict(type='str', required=True, no_log=True), http_login_user=dict(type='str', required=False, default=None), http_login_password=dict(type='str', required=False, default=None, no_log=True), host_groups=dict(type='list', required=True, aliases=['host_group']), state=dict(default="present", choices=['present', 'absent']), timeout=dict(type='int', default=10)), supports_check_mode=True) if not HAS_ZABBIX_API: module.fail_json( msg= "Missing requried zabbix-api module (check docs or install with: pip install zabbix-api)" ) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] host_groups = module.params['host_groups'] state = module.params['state'] timeout = module.params['timeout'] zbx = None # login to zabbix try: zbx = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password) zbx.login(login_user, login_password) except Exception, e: module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)
def __init__(self): self.defaultgroup = 'group_all' self.zabbix_server = None self.zabbix_username = None self.zabbix_password = None self.meta = {} self.read_settings() self.read_cli() if self.zabbix_server and self.zabbix_username: try: api = ZabbixAPI(server=self.zabbix_server) api.login(user=self.zabbix_username, password=self.zabbix_password) except BaseException as e: print( "Error: Could not login to Zabbix server. Check your zabbix.ini.", file=sys.stderr) print("Error message was: " + str(e)) sys.exit(1) if self.options.host: data = self.get_host(api, self.options.host) print(json.dumps(data, indent=2)) elif self.options.list: data = self.get_list(api) print(json.dumps(data, indent=2)) else: print("usage: --list ..OR.. --host <hostname>", file=sys.stderr) sys.exit(1) else: print( "Error: Configuration of server and credentials are required. See zabbix.ini.", file=sys.stderr) sys.exit(1)
def main(): """delete_zabbix_hosts config.yml に登録されている Default Groups に登録されているHost全てを削除する。 """ with open(yaml_path) as f: config = yaml.load(f) zapi = ZabbixAPI(server=config['zabbix']['server']) logger.info("Zabbix login: %s" % config['zabbix']['server']) zapi.login(config['zabbix']['username'], config['zabbix']['password']) groups = [zabbix.HostGroup(zapi, g) for g in config['general']['default_groups']] groupids = [g['groupid'] for g in groups] params = {'groupids': groupids} res = zapi.host.get(params) hostids = [h['hostid'] for h in res] if hostids: logger.info("Delete %s Hosts." % len(hostids)) zapi.host.delete(hostids)
def __init__(self, module, zbx=None): self._module = module if not HAS_ZABBIX_API: module.fail_json(msg=missing_required_lib('zabbix-api', url='https://pypi.org/project/zabbix-api/'), exception=ZBX_IMP_ERR) # check if zbx is already instantiated or not if zbx is not None and isinstance(zbx, ZabbixAPI): self._zapi = zbx else: server_url = module.params['server_url'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] validate_certs = module.params['validate_certs'] timeout = module.params['timeout'] self._zapi = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password, validate_certs=validate_certs) self.login() self._zbx_api_version = self._zapi.api_version()
def addHostZabbix(hostname, ipAddr, type): # login to zabbix server zapi = ZabbixAPI(server=ZAB_CONF['server'], path="", log_level=6) zapi.login(ZAB_CONF['username'], ZAB_CONF['password']) # Select win or linux group if type == 'win-server': group_id = ZAB_CONF['win_group_id'] template_id = ZAB_CONF['win_template_id'] elif type == 'cb-server': group_id = ZAB_CONF['lin_group_id'] template_id = ZAB_CONF['lin_template_id'] # Form string for Json request string = {'host':hostname,'ip':ipAddr,'dns':'','port':'10050','useip':1} string["groups"] = {'groupid': group_id} string ["templates"] = {'templateid': template_id} # Create host "string" createdhost=zapi.host.create(string)
class ZbxOperation: def __init__(self, url, username, password): self.api = ZabbixAPI(server=url) self.api.login(username, password) def get_trigger_id(self, host_name, trigger_name): result = self.api.trigger.get( {"filter": { "host": host_name, "name": trigger_name, }}) return result[0]['triggerid'] def delete_trigger_dependency(self, trigger_id): self.api.trigger.deletedependencies({"triggerid": trigger_id}) def add_trigger_dependency(self, trigger_id, depend_on_id): self.api.trigger.adddependencies({ "triggerid": trigger_id, "dependsOnTriggerid": depend_on_id })
def __init__(self): self.defaultgroup = 'group_all' self.zabbix_server = None self.zabbix_username = None self.zabbix_password = None self.validate_certs = True self.read_host_inventory = False self.use_host_interface = True self.meta = {} self.read_settings() self.read_cli() if self.zabbix_server and self.zabbix_username: try: api = ZabbixAPI(server=self.zabbix_server, validate_certs=self.validate_certs) api.login(user=self.zabbix_username, password=self.zabbix_password) # zabbix_api tries to exit if it cannot parse what the zabbix server returned # so we have to use SystemExit here except (Exception, SystemExit) as e: print("Error: Could not login to Zabbix server. Check your zabbix.ini.", file=sys.stderr) sys.exit(1) if self.options.host: data = self.get_host(api, self.options.host) print(json.dumps(data, indent=2)) elif self.options.list: data = self.get_list(api) print(json.dumps(data, indent=2)) else: print("usage: --list ..OR.. --host <hostname>", file=sys.stderr) sys.exit(1) else: print("Error: Configuration of server and credentials are required. See zabbix.ini.", file=sys.stderr) sys.exit(1)
def __init__(self, region, access_key, secret, pref_if, zbx_url, zbx_user, zbx_pass, set_macro): self.region = region self.access_key = access_key self.secret = secret self.pref_if = pref_if self.zbx_url = zbx_url self.zbx_user = zbx_user self.zbx_pass = zbx_pass self.set_macro = set_macro self.ec2 = boto3.resource('ec2', region_name=region, aws_access_key_id=access_key, aws_secret_access_key=secret) self.client = boto3.client('autoscaling', region_name=region, aws_access_key_id=access_key, aws_secret_access_key=secret) self.zapi = ZabbixAPI(server=self.zbx_url) self.zapi.login(self.zbx_user, self.zbx_pass)
def init(self): """Initialize zapi and try to login""" if not self.enabled: raise MonitoringError('Zabbix support is disabled') self.reset_cache() if self.zapi and self.zapi.logged_in: self.log(INFO, 'Reusing zabbix connection to "%s"', self.zapi.server) self.login_error = None self.connected = True else: settings = self.settings self.log(INFO, 'Establishing zabbix connection to "%s"', settings.MON_ZABBIX_SERVER) self.connected = False self.zapi = ZabbixAPI( server=settings.MON_ZABBIX_SERVER, user=settings.MON_ZABBIX_HTTP_USERNAME, passwd=settings.MON_ZABBIX_HTTP_PASSWORD, timeout=settings.MON_ZABBIX_TIMEOUT, log_level=WARNING, ssl_verify=settings.MON_ZABBIX_SERVER_SSL_VERIFY) # Login and save zabbix credentials try: self.zapi.login(settings.MON_ZABBIX_USERNAME, settings.MON_ZABBIX_PASSWORD, save=True) except ZabbixAPIException as e: err = 'Zabbix API login error (%s)' % e self.log(CRITICAL, err) self.login_error = err else: self.login_error = None self.connected = True return self.connected
def helloword(request): zapi = ZabbixAPI(server="http://192.168.0.194/zabbix/api_jsonrpc.php") zapi.login("Admin", "zabbix") # 鉴权 abc = zapi.trigger.get({"expandExpression":"extend","triggerids":range(0,100 )}) a = abc zabbix_url = "http://192.168.0.194/zabbix/api_jsonrpc.php" zabbix_header = {"Content-Type": "application/json"} zabbix_user = "******" zabbix_pass = "******" auth_code = "" result_value = [] itemid = '' memorysize = '' # 用户认证信息的部分,最终的目的是得到一个SESSIONID # 这里是生成一个json格式的数据,用户名和密码 auth_data = json.dumps( { "jsonrpc": "2.0", "method": "user.login", "params": { "user": zabbix_user, "password": zabbix_pass }, "id": 0 }) # 创建 request 对象 构造请求数据 request = urllib2.Request(zabbix_url, auth_data) for key in zabbix_header: request.add_header(key, zabbix_header[key]) # 认证和获取sessionid try: result = urllib2.urlopen(request) # 对于出错的处理 except HTTPError, e: print 'The server couldn\'t fulfill the request, Error code: ', e.code
def __init__(self, maas_endpoint): """ Initialize the RCBaaS Monitor object """ # Connect to MaaS if maas_endpoint is None: self.maas_endpoint = '160.85.4.27' else: self.maas_endpoint = maas_endpoint self.server = 'http://' + self.maas_endpoint + '/zabbix' self.username = MAAS_UID self.password = MAAS_PWD self.connFailed = False self.metrics = [ RCB_CPU, RCB_LOAD, RCB_TOTAL_MEMORY, RCB_AVAILABLE_MEMORY ] # Zabbix API self.zapi = ZabbixAPI(server=self.server) for i in range(1, 4): try: print('*** Connecting to MaaS') self.zapi.login(self.username, self.password) print('*** Connected to MaaS') self.connFailed = False except Exception as e: #print('*** Caught exception: %s: %s' % (e.__class__, e)) #traceback.print_exc() print('*** Connection to MaaS has failed! Retrying (' + str(i) + ').') self.connFailed = True time.sleep(3) if self.connFailed: print( '*** Connection to MaaS has failed! Waiting for an update to try again.' ) self.__metrics = []
class ZapiWrapper(object): """ A simple wrapper over the Zabbix API """ def __init__(self, module, zbx=None): self._module = module if not HAS_ZABBIX_API: module.fail_json(msg=missing_required_lib('zabbix-api', url='https://pypi.org/project/zabbix-api/'), exception=ZBX_IMP_ERR) # check if zbx is already instantiated or not if zbx is not None and isinstance(zbx, ZabbixAPI): self._zapi = zbx else: server_url = module.params['server_url'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] validate_certs = module.params['validate_certs'] timeout = module.params['timeout'] self._zapi = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password, validate_certs=validate_certs) self.login() self._zbx_api_version = self._zapi.api_version() def login(self): # check if api already logged in if not self._zapi.auth != '': try: login_user = self._module.params['login_user'] login_password = self._module.params['login_password'] self._zapi.login(login_user, login_password) atexit.register(self._zapi.logout) except Exception as e: self._module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)
def test_monitoring(Command, Ansible): from zabbix_api import ZabbixAPI zbx_if = Ansible("setup")['ansible_facts']['ansible_enp0s8'] zbx_ip = zbx_if['ipv4']['address'] zbx = ZabbixAPI("http://%s" % zbx_ip, timeout=10) zbx.login("Admin", "zabbix") zbx_host_list = get_host_by_host_name(zbx, "Redis") assert len(zbx_host_list) == 1 zbx_host = zbx_host_list[0]['hostid'] item = zbx.item.get( { "output": ["lastvalue"], "hostids": zbx_host, "search": { "key_": "net.tcp.port" }, "startSearch": "true" } ) assert item[0]['lastvalue'] == '1' Command.run_expect([0], "systemctl stop redis") check_item(zbx, zbx_host, "net.tcp.port", '0', 120) Command.run_expect([0], "systemctl start redis") check_item(zbx, zbx_host, "net.tcp.port", '1', 120)
def map_create(args): #Function creates value maps in Zabbix server via API result = False value_map = parse_mib(args.mib_file, args.value) if args.map_name: name = args.map_name else: name = args.value value_map_rq = {"name": name, "mappings": value_map} zbx_srv = ZabbixAPI(server=args.server) try: zbx_srv.login(user=args.user, password=args.password) print "Zabbix API Version: %s" % zbx_srv.api_version() print "Logged in: %s" % str(zbx_srv.test_login()) except ZabbixAPIException, e: sys.exit(error_parse(e))
def host_index(request): zapi = ZabbixAPI(server="http://yjy.zabbix.letiku.net:18989", user='******', passwd='Yjy@yunwei123') zapi.login('admin', 'Yjy@yunwei123') host_param = { "output": ["hostid", "name"], "selectParentTemplates": ["templateid", "name"], "filter": { "host": "" } } json_obj = zapi.json_obj(method='host.get', params=host_param) r = zapi.do_request(json_obj=json_obj) rs = r['result'] return render(request, 'hosts.html', {"host_info": rs})
def main(): module = AnsibleModule(argument_spec=dict( server_url=dict(type='str', required=True, aliases=['url']), login_user=dict(type='str', required=True), login_password=dict(type='str', required=True, no_log=True), http_login_user=dict(type='str', required=False, default=None), http_login_password=dict(type='str', required=False, default=None, no_log=True), validate_certs=dict(type='bool', required=False, default=True), alias=dict(type='str', required=True), timeout=dict(type='int', default=10)), supports_check_mode=True) if not HAS_ZABBIX_API: module.fail_json(msg=missing_required_lib( 'zabbix-api', url='https://pypi.org/project/zabbix-api/'), exception=ZBX_IMP_ERR) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] validate_certs = module.params['validate_certs'] alias = module.params['alias'] timeout = module.params['timeout'] zbx = None # login to zabbix try: zbx = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password, validate_certs=validate_certs) zbx.login(login_user, login_password) atexit.register(zbx.logout) except Exception as e: module.fail_json(msg="Failed to connect to Zabbix server: %s" % e) user = User(module, zbx) zabbix_user = user.get_user_by_user_alias(alias) zbx.logout() module.exit_json(changed=False, zabbix_user=zabbix_user)
def main(): module = AnsibleModule(argument_spec=dict( server_url=dict(type='str', required=True, aliases=['url']), login_user=dict(type='str', required=True), login_password=dict(type='str', required=True, no_log=True), http_login_user=dict(type='str', required=False, default=None), http_login_password=dict(type='str', required=False, default=None, no_log=True), validate_certs=dict(type='bool', required=False, default=True), timeout=dict(type='int', default=10), screens=dict(type='list', elements='dict', required=True, options=dict( screen_name=dict(type='str', required=True), host_group=dict(type='str'), state=dict(type='str', default='present', choices=['absent', 'present']), graph_names=dict(type='list', elements='str'), graph_width=dict(type='int', default=None), graph_height=dict(type='int', default=None), graphs_in_row=dict(type='int', default=3), sort=dict(default=False, type='bool'), ), required_if=[['state', 'present', ['host_group']]])), supports_check_mode=True) if not HAS_ZABBIX_API: module.fail_json(msg=missing_required_lib( 'zabbix-api', url='https://pypi.org/project/zabbix-api/'), exception=ZBX_IMP_ERR) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] validate_certs = module.params['validate_certs'] timeout = module.params['timeout'] screens = module.params['screens'] zbx = None # login to zabbix try: zbx = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password, validate_certs=validate_certs) zbx.login(login_user, login_password) atexit.register(zbx.logout) except Exception as e: module.fail_json(msg="Failed to connect to Zabbix server: %s" % e) screen = Screen(module, zbx) created_screens = [] changed_screens = [] deleted_screens = [] for zabbix_screen in screens: screen_name = zabbix_screen['screen_name'] screen_id = screen.get_screen_id(screen_name) state = zabbix_screen['state'] sort = zabbix_screen['sort'] if state == "absent": if screen_id: screen_item_list = screen.get_screen_items(screen_id) screen_item_id_list = [] for screen_item in screen_item_list: screen_item_id = screen_item['screenitemid'] screen_item_id_list.append(screen_item_id) screen.delete_screen_items(screen_id, screen_item_id_list) screen.delete_screen(screen_id, screen_name) deleted_screens.append(screen_name) else: host_group = zabbix_screen['host_group'] graph_names = zabbix_screen['graph_names'] graphs_in_row = zabbix_screen['graphs_in_row'] graph_width = zabbix_screen['graph_width'] graph_height = zabbix_screen['graph_height'] host_group_id = screen.get_host_group_id(host_group) hosts = screen.get_host_ids_by_group_id(host_group_id, sort) screen_item_id_list = [] resource_id_list = [] graph_ids, v_size = screen.get_graph_ids(hosts, graph_names) h_size, v_size = screen.get_hsize_vsize(hosts, v_size, graphs_in_row) if not screen_id: # create screen screen_id = screen.create_screen(screen_name, h_size, v_size) screen.create_screen_items(screen_id, hosts, graph_names, graph_width, graph_height, h_size, graphs_in_row) created_screens.append(screen_name) else: screen_item_list = screen.get_screen_items(screen_id) for screen_item in screen_item_list: screen_item_id = screen_item['screenitemid'] resource_id = screen_item['resourceid'] screen_item_id_list.append(screen_item_id) resource_id_list.append(resource_id) # when the screen items changed, then update if graph_ids != resource_id_list: deleted = screen.delete_screen_items( screen_id, screen_item_id_list) if deleted: screen.update_screen(screen_id, screen_name, h_size, v_size) screen.create_screen_items(screen_id, hosts, graph_names, graph_width, graph_height, h_size, graphs_in_row) changed_screens.append(screen_name) if created_screens and changed_screens: module.exit_json( changed=True, result= "Successfully created screen(s): %s, and updated screen(s): %s" % (",".join(created_screens), ",".join(changed_screens))) elif created_screens: module.exit_json(changed=True, result="Successfully created screen(s): %s" % ",".join(created_screens)) elif changed_screens: module.exit_json(changed=True, result="Successfully updated screen(s): %s" % ",".join(changed_screens)) elif deleted_screens: module.exit_json(changed=True, result="Successfully deleted screen(s): %s" % ",".join(deleted_screens)) else: module.exit_json(changed=False)
def main(): module = AnsibleModule( argument_spec=dict( server_url=dict(type='str', required=True, aliases=['url']), login_user=dict(type='str', required=True), login_password=dict(type='str', required=True, no_log=True), http_login_user=dict(type='str', required=False, default=None), http_login_password=dict(type='str', required=False, default=None, no_log=True), validate_certs=dict(type='bool', required=False, default=True), name=dict(type='str', required=True), parent=dict(type='str', required=False), sla=dict(type='float', required=False), calculate_sla=dict(type='bool', required=False, default=False), algorithm=dict(default='one_child', required=False, choices=['no', 'one_child', 'all_children']), trigger_name=dict(type='str', required=False), trigger_host=dict(type='str', required=False), state=dict(default="present", choices=['present', 'absent']), timeout=dict(type='int', default=10) ), supports_check_mode=True ) if not HAS_ZABBIX_API: module.fail_json(msg=missing_required_lib('zabbix-api', url='https://pypi.org/project/zabbix-api/'), exception=ZBX_IMP_ERR) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] validate_certs = module.params['validate_certs'] name = module.params['name'] parent = module.params['parent'] sla = module.params['sla'] calculate_sla = module.params['calculate_sla'] algorithm = module.params['algorithm'] trigger_name = module.params['trigger_name'] trigger_host = module.params['trigger_host'] state = module.params['state'] timeout = module.params['timeout'] zbx = None # Login to zabbix try: zbx = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password, validate_certs=validate_certs) zbx.login(login_user, login_password) atexit.register(zbx.logout) except ZabbixAPIException as error: module.fail_json(msg="Failed to connect to Zabbix server: %s" % error) # Load service module service = Service(module, zbx) service_ids = service.get_service_ids(name) if service_ids: service_json = service.dump_services(service_ids) # Delete service if state == "absent": if not service_ids: module.exit_json(changed=False, msg="Service not found, no change: %s" % name) service.delete_service(service_ids) module.exit_json(changed=True, result="Successfully deleted service(s) %s" % name) elif state == "present": if (trigger_name and not trigger_host) or (trigger_host and not trigger_name): module.fail_json(msg="Specify either both trigger_host and trigger_name or none to create or update a service") # Does not exists going to create it if not service_ids: service.create_service(name, parent, sla, calculate_sla, trigger_name, trigger_host, algorithm) module.exit_json(changed=True, msg="Service %s created" % name) # Else we update it if needed else: service.update_service(service_ids[0], name, parent, sla, calculate_sla, trigger_name, trigger_host, algorithm)
# importando a class zabbix-api from zabbix_api import ZabbixAPI import config zapi = ZabbixAPI(server=config.url) zapi.login(config.login, config.passwd) #hostid = ('d', [13328,11053,15732]) hostid = open("/Users/victor/codigos/Workspace/Zabbix/hostid.txt") linha = [line.strip() for line in hostid] hostid.close() for line in linha: items = zapi.item.get({ "output": ["itemid", "name", "key_"], "hostids": line }) for x in items: #print hosts print(line, "*", ["itemid"], "*", x["name"], "*", x["key_"])
def main(): module = AnsibleModule( argument_spec=dict( server_url=dict(type='str', required=True, aliases=['url']), login_user=dict(type='str', required=True), login_password=dict(type='str', required=True, no_log=True), http_login_user=dict(type='str', required=False, default=None), http_login_password=dict(type='str', required=False, default=None, no_log=True), validate_certs=dict(type='bool', required=False, default=True), template_name=dict(type='str', required=False), template_json=dict(type='json', required=False), template_xml=dict(type='str', required=False), template_groups=dict(type='list', required=False), link_templates=dict(type='list', required=False), clear_templates=dict(type='list', required=False), macros=dict(type='list', required=False), dump_format=dict(type='str', required=False, default='json', choices=['json', 'xml']), state=dict(type='str', default="present", choices=['present', 'absent', 'dump']), timeout=dict(type='int', default=10) ), required_one_of=[ ['template_name', 'template_json', 'template_xml'] ], mutually_exclusive=[ ['template_name', 'template_json', 'template_xml'] ], required_if=[ ['state', 'absent', ['template_name']], ['state', 'dump', ['template_name']] ], supports_check_mode=True ) if not HAS_ZABBIX_API: module.fail_json(msg=missing_required_lib('zabbix-api', url='https://pypi.org/project/zabbix-api/'), exception=ZBX_IMP_ERR) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] validate_certs = module.params['validate_certs'] template_name = module.params['template_name'] template_json = module.params['template_json'] template_xml = module.params['template_xml'] template_groups = module.params['template_groups'] link_templates = module.params['link_templates'] clear_templates = module.params['clear_templates'] template_macros = module.params['macros'] dump_format = module.params['dump_format'] state = module.params['state'] timeout = module.params['timeout'] zbx = None try: zbx = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password, validate_certs=validate_certs) zbx.login(login_user, login_password) atexit.register(zbx.logout) except ZabbixAPIException as e: module.fail_json(msg="Failed to connect to Zabbix server: %s" % e) template = Template(module, zbx) # Identify template names for IDs retrieval # Template names are expected to reside in ['zabbix_export']['templates'][*]['template'] for both data types template_content, template_type = None, None if template_json is not None: template_type = 'json' template_content = template_json json_parsed = template.load_json_template(template_content) template_names = list(t['template'] for t in json_parsed['zabbix_export']['templates']) elif template_xml is not None: template_type = 'xml' template_content = template_xml xml_parsed = template.load_xml_template(template_content) template_names = list(t.find('template').text for t in list(xml_parsed.find('templates'))) else: template_names = [template_name] template_ids = template.get_template_ids(template_names) if state == "absent": if not template_ids: module.exit_json(changed=False, msg="Template not found. No changed: %s" % template_name) template.delete_template(template_ids) module.exit_json(changed=True, result="Successfully deleted template %s" % template_name) elif state == "dump": module.deprecate("The 'dump' state has been deprecated and will be removed, use 'zabbix_template_info' module instead.", version='2.14') if not template_ids: module.fail_json(msg='Template not found: %s' % template_name) if dump_format == 'json': module.exit_json(changed=False, template_json=template.dump_template(template_ids, template_type='json')) elif dump_format == 'xml': module.exit_json(changed=False, template_xml=template.dump_template(template_ids, template_type='xml')) elif state == "present": # Load all subelements for template that were provided by user group_ids = None if template_groups is not None: group_ids = template.get_group_ids_by_group_names(template_groups) link_template_ids = None if link_templates is not None: link_template_ids = template.get_template_ids(link_templates) clear_template_ids = None if clear_templates is not None: clear_template_ids = template.get_template_ids(clear_templates) if template_macros is not None: # Zabbix configuration.export does not differentiate python types (numbers are returned as strings) for macroitem in template_macros: for key in macroitem: macroitem[key] = str(macroitem[key]) if not template_ids: # Assume new templates are being added when no ID's were found if template_content is not None: template.import_template(template_content, template_type) module.exit_json(changed=True, result="Template import successful") else: if group_ids is None: module.fail_json(msg='template_groups are required when creating a new Zabbix template') template.add_template(template_name, group_ids, link_template_ids, template_macros) module.exit_json(changed=True, result="Successfully added template: %s" % template_name) else: changed = template.check_template_changed(template_ids, template_groups, link_templates, clear_templates, template_macros, template_content, template_type) if module.check_mode: module.exit_json(changed=changed) if changed: if template_type is not None: template.import_template(template_content, template_type) else: template.update_template(template_ids, group_ids, link_template_ids, clear_template_ids, template_macros) module.exit_json(changed=changed, result="Template successfully updated")
def main(): module = AnsibleModule( argument_spec=dict( state=dict(required=False, default='present', choices=['present', 'absent']), server_url=dict(type='str', required=True, default=None, aliases=['url']), host_names=dict(type='list', required=False, default=None, aliases=['host_name']), minutes=dict(type='int', required=False, default=10), host_groups=dict(type='list', required=False, default=None, aliases=['host_group']), login_user=dict(type='str', required=True), login_password=dict(type='str', required=True, no_log=True), http_login_user=dict(type='str', required=False, default=None), http_login_password=dict(type='str', required=False, default=None, no_log=True), name=dict(type='str', required=True), desc=dict(type='str', required=False, default="Created by Ansible"), collect_data=dict(type='bool', required=False, default=True), timeout=dict(type='int', default=10), ), supports_check_mode=True, ) if not HAS_ZABBIX_API: module.fail_json( msg= "Missing requried zabbix-api module (check docs or install with: pip install zabbix-api)" ) host_names = module.params['host_names'] host_groups = module.params['host_groups'] state = module.params['state'] login_user = module.params['login_user'] login_password = module.params['login_password'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] minutes = module.params['minutes'] name = module.params['name'] desc = module.params['desc'] server_url = module.params['server_url'] collect_data = module.params['collect_data'] timeout = module.params['timeout'] if collect_data: maintenance_type = 0 else: maintenance_type = 1 try: zbx = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password) zbx.login(login_user, login_password) except BaseException as e: module.fail_json(msg="Failed to connect to Zabbix server: %s" % e) changed = False if state == "present": now = datetime.datetime.now() start_time = time.mktime(now.timetuple()) period = 60 * int(minutes) # N * 60 seconds if host_groups: (rc, group_ids, error) = get_group_ids(zbx, host_groups) if rc != 0: module.fail_json(msg="Failed to get group_ids: %s" % error) else: group_ids = [] if host_names: (rc, host_ids, error) = get_host_ids(zbx, host_names) if rc != 0: module.fail_json(msg="Failed to get host_ids: %s" % error) else: host_ids = [] (rc, maintenance, error) = get_maintenance_id(zbx, name) if rc != 0: module.fail_json( msg="Failed to check maintenance %s existance: %s" % (name, error)) if not maintenance: if not host_names and not host_groups: module.fail_json( msg= "At least one host_name or host_group must be defined for each created maintenance." ) if module.check_mode: changed = True else: (rc, _, error) = create_maintenance(zbx, group_ids, host_ids, start_time, maintenance_type, period, name, desc) if rc == 0: changed = True else: module.fail_json(msg="Failed to create maintenance: %s" % error) if state == "absent": (rc, maintenance, error) = get_maintenance_id(zbx, name) if rc != 0: module.fail_json( msg="Failed to check maintenance %s existance: %s" % (name, error)) if maintenance: if module.check_mode: changed = True else: (rc, _, error) = delete_maintenance(zbx, maintenance) if rc == 0: changed = True else: module.fail_json(msg="Failed to remove maintenance: %s" % error) module.exit_json(changed=changed)
def main(): module = AnsibleModule( argument_spec=dict( server_url=dict(type='str', required=True, aliases=['url']), login_user=dict(type='str', required=True), login_password=dict(type='str', required=True, no_log=True), http_login_user=dict(type='str', required=False, default=None), http_login_password=dict(type='str', required=False, default=None, no_log=True), validate_certs=dict(type='bool', required=False, default=True), host_name=dict(type='str', required=True), macro_name=dict(type='str', required=True), macro_value=dict(type='str', required=False), state=dict(type='str', default='present', choices=['present', 'absent']), timeout=dict(type='int', default=10), force=dict(type='bool', default=True) ), supports_check_mode=True ) if not HAS_ZABBIX_API: module.fail_json(msg=missing_required_lib('zabbix-api', url='https://pypi.org/project/zabbix-api/'), exception=ZBX_IMP_ERR) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] validate_certs = module.params['validate_certs'] host_name = module.params['host_name'] macro_name = (module.params['macro_name']) macro_value = module.params['macro_value'] state = module.params['state'] timeout = module.params['timeout'] force = module.params['force'] if ':' in macro_name: macro_name = ':'.join([macro_name.split(':')[0].upper(), ':'.join(macro_name.split(':')[1:])]) else: macro_name = macro_name.upper() zbx = None # login to zabbix try: zbx = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password, validate_certs=validate_certs) zbx.login(login_user, login_password) atexit.register(zbx.logout) except Exception as e: module.fail_json(msg="Failed to connect to Zabbix server: %s" % e) host_macro_class_obj = HostMacro(module, zbx) if host_name: host_id = host_macro_class_obj.get_host_id(host_name) host_macro_obj = host_macro_class_obj.get_host_macro(macro_name, host_id) if state == 'absent': if not host_macro_obj: module.exit_json(changed=False, msg="Host Macro %s does not exist" % macro_name) else: # delete a macro host_macro_class_obj.delete_host_macro(host_macro_obj, macro_name) else: if not host_macro_obj: # create host macro host_macro_class_obj.create_host_macro(macro_name, macro_value, host_id) elif force: # update host macro host_macro_class_obj.update_host_macro(host_macro_obj, macro_name, macro_value) else: module.exit_json(changed=False, result="Host macro %s already exists and force is set to no" % macro_name)
import csv # pip install pyzabbix #from pyzabbix import ZabbixAPI from zabbix_api import ZabbixAPI import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) import sys sys.path.insert(0, '/var/lib/zabbix') # pip install config import config ZABBIX_SERVER = config.url zapi = ZabbixAPI(ZABBIX_SERVER) zapi.session.verify = False zapi.login(config.username, config.password) file = open("hostlist.csv", 'rb') reader = csv.DictReader(file) # take the file and read line by line for line in reader: # check if this host exists in zabbix if not zapi.host.get({"filter": {"host": line['name']}}): print line['name'], "not yet registred" if zapi.proxy.get({ "output": "proxyid", "selectInterface": "extend",
def main(): module = AnsibleModule( argument_spec=dict( state=dict(required=False, default='present', choices=['present', 'absent']), server_url=dict(type='str', required=True, default=None, aliases=['url']), host_names=dict(type='list', required=False, default=None, aliases=['host_name']), minutes=dict(type='int', required=False, default=10), host_groups=dict(type='list', required=False, default=None, aliases=['host_group']), login_user=dict(type='str', required=True), login_password=dict(type='str', required=True, no_log=True), validate_certs=dict(type='bool', required=False, default=True), http_login_user=dict(type='str', required=False, default=None), http_login_password=dict(type='str', required=False, default=None, no_log=True), name=dict(type='str', required=True), desc=dict(type='str', required=False, default="Created by Ansible"), collect_data=dict(type='bool', required=False, default=True), timeout=dict(type='int', default=10), ), supports_check_mode=True, ) if not HAS_ZABBIX_API: module.fail_json(msg=missing_required_lib( 'zabbix-api', url='https://pypi.org/project/zabbix-api/'), exception=ZBX_IMP_ERR) host_names = module.params['host_names'] host_groups = module.params['host_groups'] state = module.params['state'] login_user = module.params['login_user'] login_password = module.params['login_password'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] validate_certs = module.params['validate_certs'] minutes = module.params['minutes'] name = module.params['name'] desc = module.params['desc'] server_url = module.params['server_url'] collect_data = module.params['collect_data'] timeout = module.params['timeout'] if collect_data: maintenance_type = 0 else: maintenance_type = 1 try: zbx = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password, validate_certs=validate_certs) zbx.login(login_user, login_password) atexit.register(zbx.logout) # zabbix_api can call sys.exit() so we need to catch SystemExit here except (Exception, SystemExit) as e: module.fail_json(msg="Failed to connect to Zabbix server: %s" % e) changed = False if state == "present": if not host_names and not host_groups: module.fail_json( msg= "At least one host_name or host_group must be defined for each created maintenance." ) now = datetime.datetime.now().replace(second=0) start_time = time.mktime(now.timetuple()) period = 60 * int(minutes) # N * 60 seconds if host_groups: (rc, group_ids, error) = get_group_ids(zbx, host_groups) if rc != 0: module.fail_json(msg="Failed to get group_ids: %s" % error) else: group_ids = [] if host_names: (rc, host_ids, error) = get_host_ids(zbx, host_names) if rc != 0: module.fail_json(msg="Failed to get host_ids: %s" % error) else: host_ids = [] (rc, maintenance, error) = get_maintenance(zbx, name) if rc != 0: module.fail_json( msg="Failed to check maintenance %s existence: %s" % (name, error)) if maintenance and ( sorted(group_ids) != sorted(maintenance["groupids"]) or sorted(host_ids) != sorted(maintenance["hostids"]) or str(maintenance_type) != maintenance["maintenance_type"] or str(int(start_time)) != maintenance["active_since"] or str(int(start_time + period)) != maintenance["active_till"]): if module.check_mode: changed = True else: (rc, _, error) = update_maintenance(zbx, maintenance["maintenanceid"], group_ids, host_ids, start_time, maintenance_type, period, desc) if rc == 0: changed = True else: module.fail_json(msg="Failed to update maintenance: %s" % error) if not maintenance: if module.check_mode: changed = True else: (rc, _, error) = create_maintenance(zbx, group_ids, host_ids, start_time, maintenance_type, period, name, desc) if rc == 0: changed = True else: module.fail_json(msg="Failed to create maintenance: %s" % error) if state == "absent": (rc, maintenance, error) = get_maintenance(zbx, name) if rc != 0: module.fail_json( msg="Failed to check maintenance %s existence: %s" % (name, error)) if maintenance: if module.check_mode: changed = True else: (rc, _, error) = delete_maintenance(zbx, maintenance["maintenanceid"]) if rc == 0: changed = True else: module.fail_json(msg="Failed to remove maintenance: %s" % error) module.exit_json(changed=changed)
def __init__(self, server, timeout, user, passwd, validate_certs, **kwargs): ZabbixAPI.__init__(self, server, timeout=timeout, user=user, passwd=passwd, validate_certs=validate_certs) self.hostinterface = ZabbixAPISubClass(self, dict({"prefix": "hostinterface"}, **kwargs))
from zabbix_api import ZabbixAPI zapi = ZabbixAPI(server="http://localhost/zabbix") zapi.login("admin","zabbix") hosts = zapi.host.get({ "output": [ "hostid", "name" ] }) interfaces = zapi.hostinterface.get({ "output":[ "hostid", "ip", "type" ] }) #For para percorrer host para verificar id for host in hosts: for interface in interfaces: if interface["hostid"] == host["hostid"]: print("hostid: {0} - name: {1} - IP: {2} - Tipo de interface: {3}"\ .format(host["hostid"], host["name"], interface["ip"], interface["type"]))
print(msg) if __name__ == '__main__': arguments = docopt(__doc__, version='Zabbix Maintenance 1.1') server_url = arguments['--server'] login_user = arguments['--user'] if arguments['--password']: login_password = arguments['--password'] else: login_password = getpass.getpass( prompt='Enter password for user %s on %s: ' % (login_user, server_url)) try: zbx = ZabbixAPI(server_url) zbx.login(login_user, login_password) except BaseException as e: _fail("Failed to connect to Zabbix server: %s" % e) if arguments['--hosts']: hosts = arguments['<targets>'] groups = [] else: hosts = [] groups = arguments['<targets>'] name = arguments['<name>'] if arguments['--no-data']: maintenance_type = 1
def __init__(self, url, username, password): self.api = ZabbixAPI(server=url) self.api.login(username, password)
def main(): module = AnsibleModule(argument_spec=dict( server_url=dict(type='str', required=True, aliases=['url']), login_user=dict(type='str', required=True), login_password=dict(type='str', required=True, no_log=True), http_login_user=dict(type='str', required=False, default=None), http_login_password=dict(type='str', required=False, default=None, no_log=True), validate_certs=dict(type='bool', required=False, default=True), host_groups=dict(type='list', required=True, aliases=['host_group']), state=dict(type='str', default="present", choices=['present', 'absent']), timeout=dict(type='int', default=10)), supports_check_mode=True) if not HAS_ZABBIX_API: module.fail_json(msg=missing_required_lib( 'zabbix-api', url='https://pypi.org/project/zabbix-api/'), exception=ZBX_IMP_ERR) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] validate_certs = module.params['validate_certs'] host_groups = module.params['host_groups'] state = module.params['state'] timeout = module.params['timeout'] zbx = None # login to zabbix try: zbx = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password, validate_certs=validate_certs) zbx.login(login_user, login_password) atexit.register(zbx.logout) except Exception as e: module.fail_json(msg="Failed to connect to Zabbix server: %s" % e) hostGroup = HostGroup(module, zbx) group_ids = [] group_list = [] if host_groups: group_ids, group_list = hostGroup.get_group_ids(host_groups) if state == "absent": # delete host groups if group_ids: delete_group_names = [] hostGroup.delete_host_group(group_ids) for group in group_list: delete_group_names.append(group['name']) module.exit_json(changed=True, result="Successfully deleted host group(s): %s." % ",".join(delete_group_names)) else: module.exit_json(changed=False, result="No host group(s) to delete.") else: # create host groups group_add_list = hostGroup.create_host_group(host_groups) if len(group_add_list) > 0: module.exit_json(changed=True, result="Successfully created host group(s): %s" % group_add_list) else: module.exit_json(changed=False)
def get_host_id(host_name): zapi = ZabbixAPI(server='http://127.0.0.1/zabbix') zapi.login('svc_monitoria', 'vk98v#m$') host_response = zapi.host.get({'filter': {'host': str(host_name.rstrip())}})#[0]['hostid'] host_id = host_response[0]['hostid'] return host_id