def main(argv): # Parse arguments and build work variables args = ArgumentParser() zabbixURL = args.Z zabbixUsername = args.u zabbixPassword = args.p hostNameFilter = args.f interfaceType = { '1': 'agent', '2': 'SNMP', '3': 'IPMI', '4': 'JMX', } bulkStatus = { '0': 'OFF', '1': 'ON', } zapi = ZabbixAPI(url=zabbixURL, user=zabbixUsername, password=zabbixPassword) if (hostNameFilter): # Filter based on the cmdline argument f = {'host': hostNameFilter} hosts = zapi.host.get(search=f, output='extend', selectTags='extend') interfaces = zapi.hostinterface.get(hostids=hosts[0]['hostid']) else: interfaces = zapi.hostinterface.get() for interface in (interfaces): print('HostID: {} - IP: {} - Type: {} - Bulk: {}'.format( interface['hostid'], interface['ip'], interfaceType[interface['type']], bulkStatus[interface['bulk']]))
def main(): (options, _) = get_options() try: client = ZabbixAPI(url=options.z_url, user=options.z_userid, password=options.z_passwd) except URLError as e: sys.exit('Failed to connect Zabbix server (%s)' % e) except ZabbixAPIException as e: sys.exit('Failed to authenticate Zabbix (%s)' % e) # get ID of MediaType for StackStorm if it exists, or None. mediatype_id = is_already_registered_mediatype(client, options) # register a new MediaType or update one which is already registered to dispatch events # to the StackStorm mediatype_id = register_media_type(client, options, mediatype_id) # get ID of Action for StackStorm if it exists, or None. action_id = is_already_registered_action(client, options) # register a Action which is associated with the registered MediaType register_action(client, mediatype_id, options, action_id) # register a Media to the Admin user register_media_to_admin(client, mediatype_id, options) print('Success to register the configurations for StackStorm to the Zabbix Server.')
def main(argv): # Parse arguments and build work variables args = ArgumentParser() zabbixURL = args.Z zabbixUsername = args.u zabbixPassword = args.p hostName = args.H macroName = args.M # API Connect print('Connecting to {}'.format(zabbixURL)) zapi = ZabbixAPI(url=zabbixURL, user=zabbixUsername, password=zabbixPassword) hostObj = zapi.host.get(search={'host': hostName}, output='hostids') print('Host {} (Id: {})'.format(hostName, hostObj[0]['hostid'])) currentMacro = zapi.usermacro.get(hostids=hostObj[0]['hostid'], filter={'macro': macroName}) if (currentMacro): newMacroValue = random.randint(1, 1001) print('{}: current value "{}" -> new value "{}"'.format( macroName, currentMacro[0]['value'], newMacroValue)) zapi.usermacro.update(hostmacroid=currentMacro[0]['hostmacroid'], value=newMacroValue) else: print('No {} macro found on host {}'.format(macroName, hostName))
def main(): global config global zapi config = configParse(config_file) config.parse() zapi = ZabbixAPI(url=config.zabbix_url, user=config.zabbix_user, password=config.zabbix_passwd) parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('-c', '--create-host', help='Provide host name if you need create host') parser.add_argument('-p', '--host-port', default='10050', help='Provide host port if you need create host') parser.add_argument('-i', '--host-ip', help='Provide host ip if you need create host') args = parser.parse_args() if args.create_host: createHost(hostName=args.create_host, hostIP=args.host_ip, hostPort=args.host_port, groupID='347', templateID='10068') else: print "Warning: Check your parameters!" sys.exit(1)
def main(argv): # Parse arguments and build work variables args = ArgumentParser() zabbixURL = args.Z zabbixUsername = args.u zabbixPassword = args.p hostNameFilter = args.f zapi = ZabbixAPI(url=zabbixURL, user=zabbixUsername, password=zabbixPassword) if (hostNameFilter): # Filter based on the cmdline argument f = {'host': hostNameFilter} hosts = zapi.host.get(search=f, output='extend', selectTags='extend') else: hosts = zapi.host.get(output='extend') if (args.e): jsonPrint(hosts) else: for host in hosts: print("ID: {} - Host: {}".format(host['hostid'], host['host']))
def connect(self): """ Metodo para conexao ao Zabbix via API """ self.zapi = ZabbixAPI(url=self._server_url, user=self._user, password=self._password) self._log.logger.debug("Conectou na API Zabbix.")
def main(zabbix, user, password, host): zapi = ZabbixAPI(url=zabbix, user=user, password=password) host_id = zapi.get_id(item_type='host', item=host) if host_id is None: create_zabbix_host(zapi=zapi, host=host) else: update_zabbix_host(zapi=zapi, host=host, host_id=host_id)
def run(self, api_method, token, **params): # Initialize client object to connect Zabbix server if token: self.client = ZabbixAPI(url=self.config['zabbix']['url']) self.auth = token else: self.connect() return self._call_api_method(self.client, api_method, params)
def __init__(self, _url, _user, _password): url = _url user = _user password = _password try: self.zapi = ZabbixAPI(url=url, user=user, password=password) except Exception as e: print 'Error in creating connection to Zabbix Api (%s)' % (url) raise Exception(e) self.metric_names_regex = [ '^(?P<metric_name>ICMP loss).*', '^(?P<metric_name>ICMP ping).*', '^(?P<metric_name>ICMP response time).*', '^(?P<metric_name>Incoming traffic) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*', '^(?P<metric_name>Outgoing traffic) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*', '^(?P<metric_name>In utilization) on (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*', '^(?P<metric_name>Out utilization) on (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*', '^(?P<metric_name>Inbound errors) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*', '^(?P<metric_name>Outbound errors) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*', '^(?P<metric_name>Percentage inbound errors) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*', '^(?P<metric_name>Percentage outbound errors) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*', '^(?P<metric_name>Incoming unicast packets) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*', '^(?P<metric_name>Outcoming unicast packets) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*', '^(?P<metric_name>Admin status) of interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*' ### ip sla pattern 1 , '^(?P<metric_name>Jitter) for CORP-.* (?:IBM-(?P<tos1>0)-|1-(?P<tos>0)-).*', '^(?P<metric_name>Packet Delay) for CORP-.* (?:IBM-(?P<tos1>0)-|1-(?P<tos>0)-).*', '^(?P<metric_name>Packet loss) for CORP.* (?:IBM-(?P<tos1>0)-|1-(?P<tos>0)-).*', '^(?P<metric_name>Jitter) for CORP-.* (?:IBM-(?P<tos1>96)-|1-(?P<tos>96)-).*', '^(?P<metric_name>Packet Delay) for CORP-.* (?:IBM-(?P<tos1>96)-|1-(?P<tos>96)-).*', '^(?P<metric_name>Packet loss) for CORP.* (?:IBM-(?P<tos1>96)-|1-(?P<tos>96)-).*', '^(?P<metric_name>Jitter) for CORP-.* (?:IBM-(?P<tos1>128)-|1-(?P<tos>128)-).*', '^(?P<metric_name>Packet Delay) for CORP-.* (?:IBM-(?P<tos1>128)-|1-(?P<tos>128)-).*', '^(?P<metric_name>Packet loss) for CORP.* (?:IBM-(?P<tos1>128)-|1-(?P<tos>128)-).*', '^(?P<metric_name>Jitter) for CORP-.* (?:IBM-(?P<tos1>184)-|1-(?P<tos>184)-).*', '^(?P<metric_name>Packet Delay) for CORP-.* (?:IBM-(?P<tos1>184)-|1-(?P<tos>184)-).*', '^(?P<metric_name>Packet loss) for CORP.* (?:IBM-(?P<tos1>184)-|1-(?P<tos>184)-).*' ### ip sla pattern 2 , '^(?P<metric_name>Jitter) for CORP-.*(?:IBM-(?P<tos1>0)-|-(?P<tos>0)-).*', '^(?P<metric_name>Packet Delay) for CORP-.*(?:IBM-(?P<tos1>0)-|-(?P<tos>0)-).*', '^(?P<metric_name>Packet loss) for CORP.*(?:IBM-(?P<tos1>0)-|-(?P<tos>0)-).*', '^(?P<metric_name>Jitter) for CORP-.*(?:IBM-(?P<tos1>96)-|-(?P<tos>96)-).*', '^(?P<metric_name>Packet Delay) for CORP-.*(?:IBM-(?P<tos1>96)-|-(?P<tos>96)-).*', '^(?P<metric_name>Packet loss) for CORP.*(?:IBM-(?P<tos1>96)-|-(?P<tos>96)-).*', '^(?P<metric_name>Jitter) for CORP-.*(?:IBM-(?P<tos1>128)-|-(?P<tos>128)-).*', '^(?P<metric_name>Packet Delay) for CORP-.*(?:IBM-(?P<tos1>128)-|-(?P<tos>128)-).*', '^(?P<metric_name>Packet loss) for CORP.*(?:IBM-(?P<tos1>128)-|-(?P<tos>128)-).*', '^(?P<metric_name>Jitter) for CORP-.*(?:IBM-(?P<tos1>184)-|-(?P<tos>184)-).*', '^(?P<metric_name>Packet Delay) for CORP-.*(?:IBM-(?P<tos1>184)-|-(?P<tos>184)-).*', '^(?P<metric_name>Packet loss) for CORP.*(?:IBM-(?P<tos1>184)-|-(?P<tos>184)-).*' ]
def connect(self): try: self.client = ZabbixAPI(url=self.config['zabbix']['url'], user=self.config['zabbix']['username'], password=self.config['zabbix']['password']) except ZabbixAPIException as e: raise ZabbixAPIException("Failed to authenticate with Zabbix (%s)" % str(e)) except URLError as e: raise URLError("Failed to connect to Zabbix Server (%s)" % str(e)) except KeyError: raise KeyError("Configuration for Zabbix pack is not set yet")
def __init__(self, template=None): ZabbixCLIArguments.__init__(self) self._configureLogging() log.debug('Parser arguments: %s', self.args) # if no arguments, jsut print help if len(sys.argv) <= 1: self.argparser.print_help() sys.exit() if not self.args.get('template'): sys.exit('Template should be specified.') self.url = self.args['server'] try: self.zapi = ZabbixAPI( self.url, user=self.args['user'], password=self.args['pass']) except: log.error('Error while trying open connection to zabbix server: %s', self.url) # If we need to delete an object and exit if self.args.get('delete'): template_id = self.zapi.get_id('template', self.args['delete'][1]) if ZabbixObject(self.zapi, {'name': self.args['delete'][2]}, template_id=template_id, obj_type=self.args['delete'][0]).delete(): log.info( '"{2}" {0} was deleted from "{1}"'.format( *self.args['delete'])) else: log.exit( 'Error while trying to delete: "{2}" {0} from "{1}"'.format( *self.args['delete'])) exit() # Set template name from __init__ params or args if template: self.template_name = template else: self.template_name = self.args.get('template') # Load template from file self.template = ZabbixTemplateFile(self.template_name, templates_dir=self.args.get('templates_dir')) self.template_id = None # When template loaded, set defaults and run apply process if self.template: self.config = ZabbixDefaults() self.apply()
def loginAPI(self, urlZB, userZB, passZB, groupHost, itemZB, rangeDay, adressDB, dbName, userDB, passDB, tblName): # Header API ZABIX_ROOT = urlZB url = ZABIX_ROOT + '/api_jsonrpc.php' payload = { "jsonrpc": "2.0", "method": "user.login", "params": { 'user': userZB, 'password': passZB, }, "auth": None, "id": 0, } headers = { 'content-type': 'application/json', } try: # Method use API zapi = ZabbixAPI(url=urlZB, user=userZB, password=passZB) # Test connection with API requestZB = requests.post(url, data=json.dumps(payload), headers=headers) resultZB = requestZB.json() json.dumps(resultZB) print("[INFO] API connected") print("[INFO] jsonrpc: {} && result: {}".format( resultZB['jsonrpc'], resultZB['result'])) sendConnection = exportDataAPIzabbix() return sendConnection.collectAPI(zapi, groupHost, itemZB, rangeDay, adressDB, dbName, userDB, passDB, tblName) except Exception as e: print("[ALERT] API not connected") print("[ALERT] Zabbix URL Error: {}".format(e)) print( "***********************************************************************************" ) sys.exit()
def run(self, api_method, token, **params): # Initialize client object to connect Zabbix server if token: self.client = ZabbixAPI(url=self.config['zabbix']['url']) self.auth = token else: self.connect() return self._call_api_method( self.client, api_method, {k: v for k, v in params.items() if v is not None}) # dont include param where v=None
def list_hosts(): zbx_host = sys.argv[1] zbx_user = sys.argv[2] zbx_pass = sys.argv[3] zbx_filter = sys.argv[4] zbx_filter_value = sys.argv[5] zbx_psk_identity = sys.argv[6] zbx_psk = sys.argv[7] zapi = ZabbixAPI(url=zbx_host, user=zbx_user, password=zbx_pass) if zbx_filter == 'host': res1 = zapi.do_request('host.get', { 'search': { 'host': zbx_filter_value }, 'output': ['hostid', 'name'] }) hosts = res1.get(u'result') if zbx_filter == 'template': res1 = zapi.do_request( 'template.get', { 'filter': { 'host': zbx_filter_value }, 'selectHosts': 'extend', 'output': ['hostid', 'name'] }) hosts = res1.get(u'result')[0].get(u'hosts') if zbx_filter == 'proxy': res1 = zapi.do_request( 'proxy.get', { 'filter': { 'host': zbx_filter_value }, 'selectHosts': 'extend', 'output': ['hostid', 'name'] }) hosts = res1.get(u'result')[0].get(u'hosts') if zbx_filter == 'host' or zbx_filter == 'template' or zbx_filter == 'proxy': print('Following hosts will be updated:') for host in hosts: print(host.get(u'name')) zapi.do_request( 'host.massupdate', { 'hosts': hosts, 'tls_connect': 2, 'tls_accept': 2, 'tls_psk_identity': zbx_psk_identity, 'tls_psk': zbx_psk })
def run(self, name, groups, ipaddrs=[], domains=[], proxy_host=None, token=None, main_if=''): # Initialize client object to connect Zabbix server if token: self.client = ZabbixAPI(url=self.config['zabbix']['url']) self.auth = token else: self.connect() # retrieve hostgroup-ids to be set to creating host object hostgroups = [ x['groupid'] for x in self.client.hostgroup.get(filter={'name': groups}) ] # make interface configurations to be set to creating host object interfaces = (self.get_interface_config_with_ipaddr(ipaddrs, main_if) + self.get_interface_config_with_domain(domains, main_if)) # Zabbix server requires one interface value at least if not interfaces: return (False, "You have to IP address or domain value at least one.") # If there is no main interface, set it for the first one. if not any([x['main'] > 0 for x in interfaces]): interfaces[0]['main'] = 1 # register a host object new_host = self.client.host.create( **{ 'host': name, 'groups': [{ 'groupid': x } for x in hostgroups], 'interfaces': interfaces, }) # register ZabbixProxy if it is necessary if proxy_host: self.set_proxy_for_host(proxy_host, new_host['hostids']) return (True, new_host)
def check_stat(hostlist): print hostlist zapi = ZabbixAPI(url=environ['ZABBIX_URL'], user=environ['ZABBIX_USER'], password=environ['ZABBIX_PASSWORD']) status = "green" for host in hostlist: result = zapi.do_request('trigger.get', { 'active': 1, 'only_true': 1, 'hostids': host })['result'] for x in xrange(len(result)): if int(result[x]['priority']) > 3: status = "red" return status
def main(): handler = logging.StreamHandler(sys.stderr) LOG = logging.getLogger() LOG.addHandler(handler) options = get_options() LOG.setLevel(logging.DEBUG if options.debug else logging.INFO) zapi = ZabbixAPI(server=options.server) try: json_data = (json.load(open(options.file, "r")) if options.file else json.loads(options.expression)) zapi.login(options.username, options.password) except Exception as e: die(str(e)) def execute_command(js): try: cls, method = js["method"].split(".", 1) except: print >> sys.stderr, "missing method name" return False try: obj = getattr(zapi, cls) except: print >> sys.stderr, "class %s not found" % cls return False try: print json.dumps( getattr(obj, method)(js.get("params", {})), **({ "indent": 4 } if options.indent else {})) except Exception as e: print >> sys.stderr, str(e) return False return True if isinstance(json_data, list): for i in json_data: if not (execute_command(i) or options.keep_going): sys.exit(1) else: if not execute_command(json_data): sys.exit(1)
def zbx_call(method, args): zapi = ZabbixAPI(url=settings.ZABBIX_URL, user=settings.ZABBIX_USER, password=settings.ZABBIX_PASSWD) args = args.replace("'", "\"") args = json.loads(args) if method == "service.get" and args.get('serviceids'): key = "" for srv_id in args['serviceids']: key += srv_id cached = cache.get(key) if cached: return cached else: result = zapi.do_request(method, args) cache.set(key, result, None) return result result = zapi.do_request(method, args) return result
def main(argv): # Parse arguments and build work variables args = ArgumentParser() zabbixURL = args.Z zabbixUsername = args.u zabbixPassword = args.p zapi = ZabbixAPI(url=zabbixURL, user=zabbixUsername, password=zabbixPassword) params = [] for triggerid in args.i.split(' '): trigObj = {"triggerid": triggerid, "status": args.s} params.append(trigObj) # Call request directly for the custom param field, instead of using zapi.trigger.update result = zapi.do_request('trigger.update', params=params) jsonPrint(result)
def main(): global config global zapi config = configParse(config_file) config.parse() zapi = ZabbixAPI(url=config.zabbix_url, user=config.zabbix_user, password=config.zabbix_passwd) parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('-l', '--link-template', help='Provide template name if you need link template') parser.add_argument('-H', '--host-name', help='Provides hostname to link template') args = parser.parse_args() if args.link_template: linkTemplate(hostName=args.host_name, templateName=args.link_template) else: print "Warning: Check your parameters!" sys.exit(1)
def main(): if sys.argv[1] == '-l': cf = CloudFlare.CloudFlare(email=cloudflare_user, token=cloudflare_token) zone = sys.argv[2] data_t = get_status(zone, cf) data_to_print = zabbix_discovery_rule(data_t) print(data_to_print) store_item_values(data_t, zone) elif sys.argv[1] == '-s': zone_name = sys.argv[2] status_key = sys.argv[3] statuscodes = get_item_values(zone_name, status_key) print(statuscodes) elif sys.argv[1] == '--create': zapi = ZabbixAPI(url=zabbix_url, user=zabbix_user, password=zabbix_password) id = create_hostgroup(zapi) for host in zabbix_hosts: try: stout = create_host(host, id, zapi) print(stout) except: error1 = 'Host ' + host + ' ya existe en la base de datos.' print(error1) else: print('Parametro invalido')
def main(argv): # Parse arguments and build work variables args = ArgumentParser() zabbixURL = args.Z zabbixUsername = args.u zabbixPassword = args.p hostName = args.H zabbixSearch = {'name': hostName} # API Connect print('Connecting to {}'.format(zabbixURL)) try: zapi = ZabbixAPI(url=zabbixURL, user=zabbixUsername, password=zabbixPassword) except Exception as e: print("Connection error:{}".format(str(e))) exit() try: hosts = zapi.host.get(search=zabbixSearch, output=['hostids', 'host', 'name']) except Exception as e: print("Host get error:{}".format(str(e))) exit() if (len(hosts) == 0): print("Can't find host {}".format(hostName)) exit() for host in hosts: items = zapi.item.get(hostids=host['hostid']) for item in items: print( "HostID: {} - Host: {} ({}) - ItemID: {} - Item name: {} - Key: {}" .format(host['hostid'], host['name'], host['host'], item['itemid'], item['name'], item['key_']))
def main(argv): # Parse arguments and build work variables args = ArgumentParser() zabbixURL = args.Z zabbixUsername = args.u zabbixPassword = args.p triggerNameFilter = args.t zapi = ZabbixAPI(url=zabbixURL, user=zabbixUsername, password=zabbixPassword) f = {'description': triggerNameFilter} triggers = zapi.trigger.get(search=f, output='extend', selectTags='extend') if (args.e): jsonPrint(triggers) else: for trigger in triggers: print("ID: {} - Status: {} - Trigger: {}".format( trigger['triggerid'], trigger['status'], trigger['description']))
import logging from zabbix.api import ZabbixAPI logging.basicConfig(level = logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') logger = logging.getLogger(__name__) z = ZabbixAPI(url='https://localhost/zabbix/', user='******', password='******') t1 = z.host.getobjects(status=1}) t2 = z.do_request('host.getobjects', {'status':1}) [host['host'] for host in t1] [host['host'] for host in t2['result']]
def login(self): return ZabbixAPI(url=self.config['zabbix']['url'], user=self.config['zabbix']['username'], password=self.config['zabbix']['password'])
print("Overriding default behavior, going to truncate all original hostgroups") # simple parse for arguments url = sys.argv[1] user = sys.argv[2] password = sys.argv[3] zhost = sys.argv[4] csvHostGroups = sys.argv[5] print "Going to connect to {} as {}".format(url,user) print ("Will try to update zabbix hostgroups for {} with groups: {}".format(zhost,csvHostGroups)) # Create ZabbixAPI class instance use_older_authenticate_method = False zapi = ZabbixAPI(url, use_older_authenticate_method, user, password) zversion = zapi.do_request('apiinfo.version') print "Zabbix API version: {}".format(zversion['result']) # first need to resolve the list of hostgroup names to proper ids candidateGroupIds=[] candidateGroups=csvHostGroups.split(",") for candidateGroup in candidateGroups: print("Trying to resolve hostgroup: {}".format(candidateGroup)) hostgroupResults = zapi.do_request('hostgroup.get', {'filter': { 'name': [ candidateGroup ] } }) #print("result {}, count {}".format( hostgroupResults['result'], len(hostgroupResults['result']) )) if len(hostgroupResults['result'])==0: print("ERROR could not resolve hostgroup to id, does not exist") exit(2)
""" Move hosts to a specific hostgroup list basing on a csv file Please refer to README.md for hosts.csv syntax """ import csv import json from zabbix.api import ZabbixAPI fileName = 'hosts.csv' zabbixServer = 'http://yourserver/zabbix/' zabbixUser = '******' zabbixPass = '******' zapi = ZabbixAPI(url=zabbixServer, user=zabbixUser, password=zabbixPass) # Read CSV file hostFile = open(fileName) hostReader = csv.reader(hostFile, delimiter=';', quotechar='|') # Uncomment if your csv has headers #headers = hostReader.next() hostData = list(hostReader) # CSV Parsing for host in hostData: wantedGroups = [] actualGroupIds = [] hostName = host[1].split("-")[0] moveHost = False
def __init__(self): conf = app_config() config_value = conf.get_config_value() self.__zapi = ZabbixAPI(url=config_value['zabbix_api_addr'][0], user=config_value['zabbix_api_user'][0], password=config_value['zabbix_api_user'][1])
zabbix_url = decode_user_attribute['zabbix_part']['zabbix_url'] zabbix_template = decode_user_attribute['zabbix_part']['zabbix_template'] # Getting Consul KV consul_kv = get_kv("cloudconductor/system_domain", ret_url_encode(os.environ['CONSUL_SECRET_KEY'])) decode_consul_kv = json.loads(consul_kv) decode_user_attribute = json.loads( base64.b64decode(decode_consul_kv[0]["Value"])) system_domain = decode_user_attribute['dns'] system_name = decode_user_attribute['name'] # Create ZabbixAPI class instance try: zapi = ZabbixAPI(url=zabbix_url, user=zabbix_user, password=zabbix_password) except Exception, e: print e, 'ZabbixAPI: Authenticate failed.' # Get Zabbix API version try: result_version = zapi.api_version() except: result_version = "2.4" # Hostgroup get hostgroup = system_name try: result_hostgroup = zapi.do_request('hostgroup.get', {'filter': {
def main(): # read the file into a string try: file = open (args.file, "r") data=file.read() except Exception as e: raise e zapi = ZabbixAPI(os.environ['ZABBIX_URL'], user=os.environ['ZABBIX_USERNAME'], password=os.environ['ZABBIX_PASSWORD']) if args.json: import_format='json' else: import_format='xml' zapi.do_request( 'configuration.import', { "format": import_format, "rules": { "applications": { "createMissing": True, "deleteMissing": True }, "discoveryRules": { "createMissing": True, "updateExisting": True, "deleteMissing": True }, "graphs": { "createMissing": True, "updateExisting": True, "deleteMissing": True }, "groups": { "createMissing": True }, "hosts": { "createMissing": True, "updateExisting": True }, "httptests": { "createMissing": True, "updateExisting": True, "deleteMissing": True }, "images": { "createMissing": False, "updateExisting": False }, "items": { "createMissing": True, "updateExisting": True, "deleteMissing": True }, "maps": { "createMissing": False, "updateExisting": False }, "screens": { "createMissing": False, "updateExisting": False }, "templateLinkage": { "createMissing": True, # supported from 4.4? "deleteMissing": True }, "templates": { "createMissing": True, "updateExisting": True }, "templateScreens": { "createMissing": True, "updateExisting": True, "deleteMissing": True }, "triggers": { "createMissing": True, "updateExisting": True, "deleteMissing": True }, "valueMaps": { "createMissing": True, "updateExisting": True } }, "source": data } )