def connectZabbix(host, user, password): zapi = zabbix_api.ZabbixAPI(server=host) try: zapi.login(user, password) except zabbix_api.ZabbixAPIException as e: print "Something went wrong. Probably wrong credentials" sys.exit(e.args[1]) return zapi
def z_logging(): status = None zabbix_info = {} zagent_info = {} zabbix_info = jmp_info('jmp.properties') #print zabbix_info logging.debug(zabbix_info) zagent_info = z_info(zabbix_info['jta_z_agent_conf']) #print zagent_info logging.debug(zagent_info) zabbix_server_username=zabbix_info['username'] zabbix_server_password=zabbix_info['password'] zabbix_server_url='http://'+ zagent_info['Server'] + '/zabbix' #print zabbix_server_url logging.debug(zabbix_server_url) z=zabbix_api.ZabbixAPI(server=zabbix_server_url) z.login(user=zabbix_server_username, password=zabbix_server_password) return z
def main(): parser = argparse.ArgumentParser( description='Add host to given Zabbix server') parser.add_argument('--zabbix', help='Zabbix server url') parser.add_argument('--zlogin', help='Zabbix login') parser.add_argument('--zpwd', help='Zabbix password') parser.add_argument('--hostname', help='Host name to be added') parser.add_argument('--hostip', help='Host ip address') parser.add_argument('--hostgroups', nargs='+', help='Host group list') parser.add_argument('--templates', nargs='+', help='Templates to be linked to given host') args = parser.parse_args() try: z = zabbix_api.ZabbixAPI("http://%s/zabbix" % args.zabbix) z.login(args.zlogin, args.zpwd) except Exception, e: print "Could not login! Caught exception: %s" % str(e) sys.exit(-1)
# Zabbix API Python usage example # Christoph Haas <*****@*****.**> # import zabbix_api import sys from datetime import datetime, timedelta import time username = '******' password = '******' zabbix_url = 'http://localhost/zabbix/api_jsonrpc.php' yesterday = datetime.now() - timedelta(days=1) yesterdaystr = str(int(time.mktime(yesterday.timetuple()))) # Connect to Zabbix server z = zabbix_api.ZabbixAPI(server=zabbix_url) z.login(user=username, password=password) # Get jsontest key data jsontest = z.history.get({ "output": "extend", "history": "4", "itemids": ["28250"], "sortfield": "clock", "sortorder": "DESC", "time_from": yesterdaystr }) # Return the last entry print(jsontest[0])
def fetch_monitoring_data_to_single_csv(hostname, key, csv_file_write, datetime_start, datetime_end, debuglevel): # Simple check before we start if datetime_start == '' and datetime_end == '': logging.error(" Need -t1 option ") exit() # # Connect to Zabbix and get a handle # zabbix_login_desc = zabbix_api.ZabbixAPI(server=SERVER, log_level=debuglevel) zabbix_login_desc.login(USERNAME, PASSWORD) # # Get host and item id to get specific Item information. # host_id = zabbix_login_desc.host.get({"filter": {"host": hostname}, "output": "extend"})[0]["hostid"] item_id = zabbix_login_desc.item.get({"filter": {"key_": key, "hostid": host_id}, "output": "extend"}) logging.debug("Host ID :" + str(host_id)) logging.debug("Item ID :" + str(item_id)) # Setting the item id item_id_number = item_id[0]["itemid"] write_string_to_file = "" # Check for start / end datetime if datetime_start != '' and datetime_end == '': date_start = datetime.datetime.strptime(datetime_start, '%Y-%m-%d %H:%M:%S') # Convert to timestamp, since no end time is given we take the current time. timestamp_start = time.mktime(date_start.timetuple()) timestamp_end = int(round(time.time())) # Query for the information history = zabbix_login_desc.history.get( {"history": item_id[0]["value_type"], "time_from": timestamp_start, "time_till": timestamp_end, "itemids": [item_id_number, ], "output": "extend"}) increment = 0 # We recieve a large dictionary, which we traverse to get our data. for history_data in history: # write each line at a time. # Picking key, clock, value information, (clock is in timestamp format) # convert timestamp to current time in %Y-%m-%d %H:%M:%S format write_string_to_file = write_string_to_file + key + ";" + \ get_datetime_from_timestamp(history_data["clock"]) + ";" + \ history_data["value"] + "\n" # Record counter increment += 1 else: # Now we have the start and end time. date_start = datetime.datetime.strptime(datetime_start, '%Y-%m-%d %H:%M:%S') date_end = datetime.datetime.strptime(datetime_end, '%Y-%m-%d %H:%M:%S') # Concert to timestamp timestamp_start = time.mktime(date_start.timetuple()) timestamp_end = time.mktime(date_end.timetuple()) # Get dictionary history = zabbix_login_desc.history.get( {"history": item_id[0]["value_type"], "time_from": timestamp_start, "time_till": timestamp_end, "itemids": [item_id_number, ], "output": "extend"}) # Start Counter increment = 0 # Traverse the dictionary (JSON) for history_data in history: # write each line at a time. # Picking key, clock, value information, (clock is in timestamp format) # convert timestamp to current time in %Y-%m-%d %H:%M:%S format write_string_to_file = write_string_to_file + key + ";" + \ get_datetime_from_timestamp(history_data["clock"]) + ";" + \ history_data["value"] + "\n" # Record Counter increment += 1 # Lets write all the values to the file. csv_file_write.write(write_string_to_file)
#!/usr/bin/env python3 import zabbix_api import json z_api = zabbix_api.ZabbixAPI(server="http://localhost/zabbix") z_api.login("Admin", "zabbix") template_ids = [] print("Exporting templates:") for template in z_api.template.get({"search":{"name": "custom_template__"}, "output": ["templateid", "name"]}): print(" ", template["name"]) template_ids += [template["templateid"]] with open("/zabbix-templates/custom_templates.json", "w") as f: # 'configuration.export' returns non-indented non-human-readable text # We use intermediate JSON object to prettify it json_text = z_api.configuration.export({"format": "json", "options": {"templates": template_ids}}) json_obj = json.loads(json_text) f.write(json.dumps(json_obj, indent=2)) z_api.logout()
#!/usr/bin/env python2.6 import zabbix_api import sys xmldir = "/vagrant/" xmlfile = xmldir + sys.argv[1] zapi = zabbix_api.ZabbixAPI(server='https://10.10.10.3/zabbix', path="", log_level=1) zapi.login('admin', 'zabbix') f = open(xmlfile) source = f.read() zapi.configuration.import_( { "format": "xml", "rules": { "groups": { "createMissing": True, "updateExisting": True }, "hosts": { "createMissing": True, "updateExisting": True }, "templates": { "createMissing": True, "updateExisting": True }, "triggers": {
parser.add_argument('--url', dest='url', default='http://localhost/zabbix', help='Zabbix server address') parser.add_argument('-u', '--user', dest='user', default='admin', help='Zabbix user') parser.add_argument('-p', '--password', dest='password', required=True, help='Zabbix password') parser.add_argument('-v', '--verbose', action='store_true', default=False, help='Verbose') subparsers = parser.add_subparsers(dest='subparser_name') parser_template = subparsers.add_parser('template', help="Add a template") parser_template.add_argument('template', type=argparse.FileType('r'), help='Template XML file') parser_template = subparsers.add_parser('autoregistration', help="Create a autoregistration action") parser_template.add_argument('-t', '--template-name', dest='template_name', default=None, help='Auto registred host is linked to this template name') args = parser.parse_args() zapi = zabbix_api.ZabbixAPI(server=args.url, path="", log_level=0) zapi.login(args.user, args.password) if args.subparser_name == "template": try: ret = zapi.configuration.import_( {'rules': { 'templates': {'createMissing': True, 'updateExisting': True}, 'items': {'createMissing': True, 'updateExisting': True}, 'graphs': {'createMissing': True, 'updateExisting': True}, 'hosts': {'createMissing': True, 'updateExisting': True}, 'screens': {'createMissing': True, 'updateExisting': True}, 'triggers': {'createMissing': True, 'updateExisting': True}, 'applications': {'createMissing': True, 'updateExisting': True}, 'discoveryRules': {'createMissing': True, 'updateExisting': True}
def fetch_monitoring_data_to_csv(username, password, server, hostname, key, output_file_name, datetime_start, datetime_end, debuglevel): # Simple check before we start if datetime_start == '' and datetime_end == '': logging.error(" Need -t1 option ") exit() # # Connect to Zabbix and get a handle # zabbix_login_desc = zabbix_api.ZabbixAPI(server=server, log_level=debuglevel) zabbix_login_desc.login(username, password) # # Get host and item id to get specific Item information. # host_id = zabbix_login_desc.host.get({ "filter": { "host": hostname }, "output": "extend" })[0]["hostid"] item_id = zabbix_login_desc.item.get({ "filter": { "key_": key, "hostid": host_id }, "output": "extend" }) logging.debug("Host ID :" + str(host_id)) logging.debug("Item ID :" + str(item_id)) # Setting the item id item_id_number = item_id[0]["itemid"] # Open a file based on the input. if output_file_name == '': output_file_name = ''.join(element for element in key if element.isalnum()) output_file_name = output_file_name + ".csv" csv_file_to_write = open(output_file_name, 'w') else: csv_file_to_write = open(output_file_name, 'w') # Writing Header write_string_to_file = "key;timestamp;value\n" # Check for start / end datetime if datetime_start != '' and datetime_end == '': date_start = datetime.datetime.strptime(datetime_start, '%Y-%m-%d %H:%M:%S') # Convert to timestamp, since no end time is given we take the current time. timestamp_start = time.mktime(date_start.timetuple()) timestamp_end = int(round(time.time())) # Query for the information history = zabbix_login_desc.history.get({ "history": item_id[0]["value_type"], "time_from": timestamp_start, "time_till": timestamp_end, "itemids": [ item_id_number, ], "output": "extend" }) increment = 0 # We recieve a large dictionary, which we traverse to get our data. for history_data in history: # write each line at a time. # Picking key, clock, value information, (clock is in timestamp format) # TODO : convert timestamp to current time in %Y-%m-%d %H:%M:%S format write_string_to_file = write_string_to_file + key + ";" + \ get_datetime_from_timestamp(history_data["clock"]) + ";" + \ history_data["value"] + "\n" # Record counter increment = increment + 1 # Done logging.info( str(increment) + " records has been fetched and saved into: " + output_file_name) else: # Now we have the start and end time. date_start = datetime.datetime.strptime(datetime_start, '%Y-%m-%d %H:%M:%S') date_end = datetime.datetime.strptime(datetime_end, '%Y-%m-%d %H:%M:%S') # Concert to timestamp timestamp_start = time.mktime(date_start.timetuple()) timestamp_end = time.mktime(date_end.timetuple()) # Get dictionary history = zabbix_login_desc.history.get({ "history": item_id[0]["value_type"], "time_from": timestamp_start, "time_till": timestamp_end, "itemids": [ item_id_number, ], "output": "extend" }) # Start Counter increment = 0 # Traverse the dictionary (JSON) for history_data in history: # write each line at a time. # Picking key, clock, value information, (clock is in timestamp format) # TODO : convert timestamp to current time in %Y-%m-%d %H:%M:%S format write_string_to_file = write_string_to_file + key + ";" + \ get_datetime_from_timestamp(history_data["clock"]) + ";" + \ history_data["value"] + "\n" # Record Counter increment = increment + 1 # Done logging.info( str(increment) + " records has been fetched and saved into: " + output_file_name) # Lets write all the values to the file. csv_file_to_write.write(write_string_to_file) # We are done lets close file. csv_file_to_write.close()