def client(**kwargs): global zapi if not zapi: zapi = ZabbixAPI(kwargs['url']) zapi.login(kwargs['username'], kwargs['password']) print zapi.api_version() return zapi
def test_get_api_version(self): zapi = ZabbixAPI(url='http://127.0.0.1', user='******', password='******') if os.environ['ZABBIX_VERSION'] == '3': self.assertEqual(zapi.api_version(), '3.0.1') elif os.environ['ZABBIX_VERSION'] == '2': self.assertEqual(zapi.api_version(), '2.4.7') else: self.fail('api_version() not tested!')
def main(argv): logging.basicConfig( format='%(asctime)s:%(process)d:[%(levelname)s](%(name)s):%(message)s', level=log_level) for module in skipmodules: logging.getLogger(module).setLevel(logging.ERROR) try: opts, args = getopt.getopt(argv, "hs:f:", ["help", "source=", "field="]) except getopt.GetoptError: helpArgs() sys.exit() for opt, arg in opts: if opt in ("-h", "--help"): helpArgs() sys.exit() elif opt in ("-s", "--source"): hostname = arg elif opt in ("-f", "--field"): fieldname = arg zapi = ZabbixAPI(ZBXURI) zapi.login(ZBXUSER, ZBXPASS) logging.info("Connected to Zabbix API %s Version %s" % (ZBXURI, zapi.api_version())) zapi.cicle_inventory_value(hostname=hostname, inventory_field=fieldname)
def loadconfig(configfile, checkssl, logging): configfile = configfile checkssl = checkssl logging = logging with open(configfile, 'r') as jsonfile: data = json.load(jsonfile) for jsoninfo in data: if 'zbx_url' in jsoninfo: zbx_url = jsoninfo['zbx_url'] if 'zbx_username' in jsoninfo: zbx_username = jsoninfo['zbx_username'] if 'zbx_password' in jsoninfo: zbx_password = jsoninfo['zbx_password'] zapi = ZabbixAPI(zbx_url) if checkssl == 'nossl': import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) zapi.session.verify = False if logging == 'log': import sys import logging stream = logging.StreamHandler(sys.stdout) stream.setLevel(logging.DEBUG) log = logging.getLogger('pyzabbix') log.addHandler(stream) log.setLevel(logging.DEBUG) zapi.login(zbx_username, zbx_password) print("Connected to Zabbix API Version %s" % zapi.api_version()) return (zapi)
def exporter(args): try: zapi = ZabbixAPI(server=args.zabbix_host) zapi.login(api_token=args.zabbix_api_token) print("Connected to Zabbix API Version %s" % zapi.api_version()) except Exception as e: print( "Failed to connect with the Zabbix API. Please check your credentials." ) print(str(e)) exit(1) if args.debug is True: stream = logging.StreamHandler(sys.stdout) stream.setLevel(logging.DEBUG) log = logging.getLogger("pyzabbix") log.addHandler(stream) log.setLevel(logging.DEBUG) if args.export_type == "templates": export_templates(zapi) elif args.export_type == "mediatypes": export_mediaTypes(zapi) elif args.export_type == "hosts": export_hosts(zapi) elif args.export_type == "hostgroups": export_hosts_groups(zapi) elif args.export_type == "maps": export_maps(zapi) elif args.export_type == "images": export_images(zapi)
def main(): # Enter administrator credentials for the Zabbix Web Frontend username = raw_input('Username: '******'dns'] != h['host']: print '%s is actually connecting to %s.' % (h['host'],h['dns']) # Make sure they are using hostnames to connect rather than IPs if h['useip'] == '1': print '%s is using IP instead of hostname. Skipping.' % h['host'] continue # Set their IP record to match what the DNS system says it should be try: lookup = socket.gethostbyaddr(h['dns']) except socket.gaierror, e: print h['dns'], e continue actual_ip = lookup[2][0] if actual_ip != h['ip']: print "%s has the wrong IP: %s. Changing it to: %s" % (h['host'], h['ip'], actual_ip) update_host_ip(zapi,h['hostid'],actual_ip)
class ZabbixGateway(object): def __init__(self): self.user = settings.ZABBIX['USER'] self.passwd = settings.ZABBIX['PASSWD'] self.zabbix = ZabbixAPI(settings.ZABBIX['HOST']) def get_version(self): return self.zabbix.api_version() def get_user(self, userid): self.zabbix.login(self.user, self.passwd) res = self.zabbix.user.get(userids=str(userid)) self.zabbix.user.logout() if len(res) == 1: return res[0]['alias'] else: return None def create_user(self, username, raw_password): """Create zabbix user. zabbix method: user.create zabbix doc: https://www.zabbix.com/documentation/3.4/manual/api/reference/user/create """ self.zabbix.login(self.user, self.passwd) groups = [ {'usrgrpid': str(settings.ZABBIX['DEFAULT_GID'])} ] # TODO catch exceptions res = self.zabbix.user.create(alias=username, passwd=raw_password, usrgrps=groups) self.zabbix.user.logout() return int(res['userids'][0])
def zabbix_login(): """ Initiate a Zabbix API session """ global ZAPI ZAPI = ZabbixAPI(ZABBIX_URL) LOGGER.info('Zabbix: Logging in into Zabbix API %s as %s', ZABBIX_URL, ZABBIX_USER) ZAPI.login(ZABBIX_USER, ZABBIX_PASSWORD) LOGGER.info('Connected to Zabbix API Version %s', ZAPI.api_version())
def auth_zabbix(server_ip, username='******', password='******'): logging.debug("Authentication - Zabbix Server") zapi = ZabbixAPI("http://" + server_ip + "/zabbix") zapi.login(username, password) logging.debug("Connected to Zabbix API Version %s" % zapi.api_version()) return zapi
def auth_zabbix(server_ip, username="******", password="******"): logging.debug("Authentication - Zabbix Server") zapi = ZabbixAPI("http://" + server_ip + "/zabbix") zapi.login(username, password) logging.debug("Connected to Zabbix API Version %s" % zapi.api_version()) return zapi
def login_check(cred, password): try: z = ZabbixAPI(cred['host'], user=cred['user'], password=password) result = True # return api version api = z.api_version() except: result = False api = None return result, api
def __createConnection(self): sendToLogger('debug', 'Connecting to zabbix-server on ' + str(self.zbx_url)) try: zapi = ZabbixAPI(self.zbx_url) zapi.login(self.zbx_user, self.zbx_pass) sendToLogger('debug', 'Connected to zabbix-server API Version ' + zapi.api_version()) return zapi except: sendToLogger('error', 'Connection to zabbix-server on ' + str(self.zbx_url) + ' failed.') exit(2)
def test_detecting_version(self): httpretty.register_uri( httpretty.POST, "http://example.com/api_jsonrpc.php", body=json.dumps({ "jsonrpc": "2.0", "result": "4.0.0", "id": 0 }), ) zapi_detect = ZabbixAPI('http://example.com') self.assertEqual(zapi_detect.api_version(), '4.0.0')
def check_cluster(host,group,trigger,display,debug): zapi = ZabbixAPI(zabbix_site) zapi.login(zabbix_user,zabbix_pass) if debug: print("Connected to Zabbix API Version {0}".format(zapi.api_version())) notok_num = 0 total_num = 0 if group: trigger_obj_notok = zapi.trigger.get(group=group,monitored=1,withLastEventUnacknowledged=1,search={'description':trigger},filter={'value':1}) trigger_obj_total = zapi.trigger.get(group=group,monitored=1,search={'description':trigger}) notok_num = len(trigger_obj_notok) total_num = len(trigger_obj_total) if host: host_name_rex = host hosts = zapi.host.get(monitored_hosts=1,output="extend") for i in range(0,len(hosts)): host_name = hosts[i]["name"] if re.match(host_name_rex,host_name): total_num += 1 trigger_obj = zapi.trigger.get(host=host_name,search={'description':trigger}) if not trigger_obj: if debug: print("No such trigger: '{0}' on host: {1}".format(trigger,host_name)) else: return False else: trigger_id = trigger_obj[0]["triggerid"] trigger_retval = trigger_obj[0]["value"] trigger_item = zapi.trigger.get(triggerids=trigger_id,withLastEventUnacknowledged=1) if trigger_item and trigger_retval == '1': if debug: print("Found host:'{0}' with trigger return value:'{1}'".format(host_name,trigger_retval)) notok_num += 1 elif trigger_retval == '1': if debug: print("Found host:'{0}' with acknowledged trigger return value:'{1}'".format(host_name,trigger_retval)) elif trigger_retval == '0': if debug: print("Found host:'{0}' with trigger return value:'{1}'".format(host_name,trigger_retval)) dicimal_number = float(notok_num) / float(total_num) if display == 'ratio': print("{0} of {1} servers not ok".format(notok_num,total_num)) if display == 'decimal': print dicimal_number return True
def _connect_to_zabbix_server_api(self): """This function will connect to the zabbix server API""" logging.info('Connecting to Zabbix server "%s" API...' % (self.zabbix_server)) try: zapi = ZabbixAPI("http://%s/zabbix" % (self.zabbix_server)) zapi.login(self.zabbix_user, self.zabbix_password) except: logging.critical('There was a problem connecting to the Zabbix server "%s" API \n' % (self.zabbix_server) + str(traceback.format_exc())) logging.critical('Will update Zabbix server and exit...') self._send_to_zabbix(self.zabbix_host_name, "Error:Web Server: failed connecting to Zabbix server API", "Web_Server_Error") logging.critical('Script will be terminated....') sys.exit(1) logging.info("Connected to Zabbix API Version %s" % zapi.api_version()) return zapi
def main(): global z #try: # opts, args = getopt.getopt(argv,"hp:s:u:",["password="******"server=", "user="******"cli-inventory.py -s -server= <server> -u -username= <username> -p -password= <password>") # sys.exit(2) #for opt, arg in opts: # if opt == '-h': # print("cli-inventory.py -s -server= <server> -u -username= <username> -p -password= <password>") # sys.exit() # elif opt in ("-s", "-server="): # serverip = arg # elif opt in ("-u", "-username="******"-p", "-password="******"Logged into ZabbixAPI version " + z.api_version()) except ZabbixAPIException as e: print(e, "\nProgram will now close.") sys.exit(2) except requests.Timeout as f: print(f, "\nProgram will now close.") sys.exit(2) else: print("Must enter a correct URL for the Zabbix server (eg. http://192.168.0.4/zabbix).") sys.exit(2) else: print("Required parameter missing.") sys.exit(2) if filepath is not None: return filepath else: return 'arbitrary'
def fetch_data(self, command): """ Récupère des données depuis le serveur à partir des critères de sélection spécifiés en paramètre :param command: critère de sélection et connexion """ super()._load_config() command.asserts() zapi = ZabbixAPI(server=self.serverUrl, timeout=2.5) datas = None try: zapi.login(command.user, command.password) self.logger.info("Try connecting to {}... Zabbix v{}...".format( self.serverUrl, zapi.api_version())) except (ZabbixAPIException, ReadTimeout, ValueError) as ex: self.logger.error("Try connecting to {} : {}".format( self.serverUrl, ex)) # adapte les params en fonction du mode d'utilisation apiParams = dict(itemids=command.itemIds, output='extend', sortfield='clock') if (command.dateEnd and command.dateStart): apiParams["time_from"] = int(command.dateStart.timestamp()) apiParams["time_till"] = int(command.dateEnd.timestamp()) apiParams["sortorder"] = "ASC" detailHistory = "{} to {}".format(command.dateStart, command.dateEnd) else: # en mode limit, il faut inverser le tri pour récupérer les valeurs # les plus récentes apiParams["limit"] = command.limit apiParams["sortorder"] = "DESC" detailHistory = "{} last values".format(command.limit) try: datas = zapi.history.get(**apiParams) self.logger.info("Fetching history from {}...{} value(s)".format( detailHistory, len(datas))) except (ZabbixAPIException, ReadTimeout, ValueError) as ex: self.logger.error("Fetching history from {} : {}".format( detailHistory, ex)) return datas
def main(): logging.basicConfig( format='%(asctime)s:%(process)d:[%(levelname)s](%(name)s):%(message)s', level=log_level) for module in skipmodules: logging.getLogger(module).setLevel(logging.ERROR) try: zapi = ZabbixAPI(ZBXURI) zapi.login(ZBXUSER, ZBXPASS) logging.info("Connected to Zabbix API %s Version %s" % (ZBXURI, zapi.api_version())) for host in zapi.all_hosts(): zapi.device_items_to_inventory(hostname=host['host']) except Exception as e: logging.critical(str(e), exc_info=logshowerror) pass
def main(url: str, login: str, passowrd: str, host: str, tg_id: str, tg_token: str) -> None: zapi = ZabbixAPI(url) zapi.login(login, passowrd) logging.info(zapi.api_version()) media_type_id = get_tg_media_type_id(zapi) # update_tg_media_type(zapi, tg_token, media_type_id) user_id = get_user_id(zapi, login) # add_tg_id_to_user_media(zapi, login, tg_id, user_id, media_type_id) # FIXME: 'Error -32602: Invalid params., Invalid parameter "/1/user_medias/1/sendto": an array is expected.', -32602) host_id, int_id = get_host_and_interface_id(zapi, host) for i in range(1, 4): create_task_item(zapi, host_id, int_id, i) create_task_trigger(zapi, i)
class ZabbixConnectionModule(object): def __init__(self, zabbix_server, zabbix_username, zabbix_password): self.zabbix_server = zabbix_server self.zabbix_username = zabbix_username self.zabbix_password = zabbix_password self.zabbix_server = ZabbixAPI(self.zabbix_server) def zabbix_api_connect(self): try: self.zabbix_server.login(self.zabbix_username, self.zabbix_password) logging.info("Connected to Zabbix API Version %s" % self.zabbix_server.api_version()) return self.zabbix_server except ZabbixAPI.ZabbixAPIException: logging.exception("Couldn't connect to Zabbix API.") sys.exit()
def get_dashboard(cfg): zapi = ZabbixAPI(url=cfg['url'], user=cfg['api_user'], password=cfg['api_pass']) v = zapi.api_version() try: boards = zapi.dashboard.get( output='extend', selectWidgets='extend', selectUsers='extend', selectUserGroups='extend', ) except Exception as inst: return "API not supports this feature" res = "*Available dashboards:\n*" res += "\n".join("{} : {}".format(b['dashboardid'], b['name']) for b in boards) return res
def setup(hass, config): """Set up the Zabbix component.""" conf = config[DOMAIN] protocol = "https" if conf[CONF_SSL] else "http" url = urljoin(f"{protocol}://{conf[CONF_HOST]}", conf[CONF_PATH]) username = conf.get(CONF_USERNAME) password = conf.get(CONF_PASSWORD) zapi = ZabbixAPI(url) try: zapi.login(username, password) _LOGGER.info("Connected to Zabbix API Version %s", zapi.api_version()) except ZabbixAPIException as login_exception: _LOGGER.error("Unable to login to the Zabbix API: %s", login_exception) return False hass.data[DOMAIN] = zapi return True
def getCredentials(zabAuth, grafAuth): """ Parameters: Zabbix Authentication file with two lines, <URL> <username> <password> Grafana Authentication file with two lines, <token> <URL> Returns: ZabbixAPI Object, token, and url """ zabbixAPI = None try: inFile = open(zabAuth, "r") ZURL = inFile.readline().strip() username = inFile.readline().strip() password = inFile.readline().strip() print(ZURL) print(username) inFile.close() except IOError: print("Couldn't open %s..." % zabAuth) sys.exit(0) zabbixAPI = ZabbixAPI(ZURL) zabbixAPI.login(username, password) print("Zabbix API version = " + zabbixAPI.api_version()) try: inFile = open(grafAuth, "r") token = inFile.readline().strip() URL = inFile.readline().strip() inFile.close() except IOError: print("Couldn't open %s..." % grafAuth) sys.exit(0) return zabbixAPI, token, URL
def setup(hass, config): """Set up the Zabbix component.""" conf = config[DOMAIN] if conf[CONF_SSL]: schema = "https" else: schema = "http" url = urljoin("{}://{}".format(schema, conf[CONF_HOST]), conf[CONF_PATH]) username = conf.get(CONF_USERNAME, None) password = conf.get(CONF_PASSWORD, None) zapi = ZabbixAPI(url) try: zapi.login(username, password) _LOGGER.info("Connected to Zabbix API Version %s", zapi.api_version()) except ZabbixAPIException as login_exception: _LOGGER.error("Unable to login to the Zabbix API: %s", login_exception) return False hass.data[DOMAIN] = zapi return True
def setup(hass, config): """Set up the Zabbix component.""" from pyzabbix import ZabbixAPI, ZabbixAPIException conf = config[DOMAIN] if conf[CONF_SSL]: schema = 'https' else: schema = 'http' url = urljoin('{}://{}'.format(schema, conf[CONF_HOST]), conf[CONF_PATH]) username = conf.get(CONF_USERNAME, None) password = conf.get(CONF_PASSWORD, None) zapi = ZabbixAPI(url) try: zapi.login(username, password) _LOGGER.info("Connected to Zabbix API Version %s", zapi.api_version()) except ZabbixAPIException: _LOGGER.error("Unable to login to the Zabbix API") return False hass.data[DOMAIN] = zapi return True
#!/usr/bin/python import sys from pyzabbix import ZabbixAPI #api_key=str(sys.argv[1]) zapi = ZabbixAPI("http://zabbix.ns2online.com.br") zapi.session.verify = False zapi.login("monitoracao", "Senha1234") zapi.timeout = 5.1 print("Conectado %s" % zapi.api_version()) #for h in zapi.host.get(output="extend"): # print(h['hostid']
class ZabbixConn(object): """ Zabbix connector class Defines methods for managing Zabbix users and groups """ def __init__(self, config, ldap_conn): self.ldap_conn = ldap_conn self.server = config.zbx_server self.username = config.zbx_username self.password = config.zbx_password self.auth = config.zbx_auth self.dryrun = config.dryrun self.nocheckcertificate = config.zbx_nocheckcertificate self.ldap_groups = config.ldap_groups self.ldap_media = config.ldap_media self.media_opt = config.media_opt self.deleteorphans = config.zbx_deleteorphans self.media_description = config.media_description self.user_opt = config.user_opt if self.nocheckcertificate: from requests.packages.urllib3 import disable_warnings disable_warnings() if config.ldap_wildcard_search: self.ldap_groups = ldap_conn.get_groups_with_wildcard() # Use logger to log information self.logger = logging.getLogger() if config.verbose: self.logger.setLevel(logging.DEBUG) else: self.logger.setLevel(logging.INFO) formatter = logging.Formatter( '%(asctime)s - %(levelname)s - %(message)s') # Log to stdout ch = logging.StreamHandler() if config.verbose: ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) self.logger.addHandler(ch) # Use logger to log information # Log from pyzabbix log = logging.getLogger('pyzabbix') log.addHandler(ch) if config.verbose: log.setLevel(logging.DEBUG) def connect(self): """ Establishes a connection to the Zabbix server Raises: SystemExit """ if self.auth == "webform": self.conn = ZabbixAPI(self.server) elif self.auth == "http": self.conn = ZabbixAPI(self.server, use_authenticate=False) self.conn.session.auth = (self.username, self.password) else: raise SystemExit('api auth method not implemented: %s' % self.conn.auth) if self.nocheckcertificate: self.conn.session.verify = False try: self.conn.login(self.username, self.password) except ZabbixAPIException as e: raise SystemExit('Cannot login to Zabbix server: %s' % e) self.logger.info("Connected to Zabbix API Version %s" % self.conn.api_version()) def get_users(self): """ Retrieves the existing Zabbix users Returns: A list of the existing Zabbix users """ result = self.conn.user.get(output='extend') users = [user['alias'] for user in result] return users def get_mediatype_id(self, description): """ Retrieves the mediatypeid by description Args: description (str): Zabbix media type description Returns: The mediatypeid for specified media type description """ result = self.conn.mediatype.get(filter={'description': description}) if result: mediatypeid = result[0]['mediatypeid'] else: mediatypeid = None return mediatypeid def get_user_id(self, user): """ Retrieves the userid of a specified user Args: user (str): The Zabbix username to lookup Returns: The userid of the specified user """ result = self.conn.user.get(output='extend') userid = [u['userid'] for u in result if u['alias'].lower() == user].pop() return userid def get_groups(self): """ Retrieves the existing Zabbix groups Returns: A dict of the existing Zabbix groups and their group ids """ result = self.conn.usergroup.get(status=0, output='extend') groups = [{ 'name': group['name'], 'usrgrpid': group['usrgrpid'] } for group in result] return groups def get_group_members(self, groupid): """ Retrieves group members for a Zabbix group Args: groupid (int): The group id Returns: A list of the Zabbix users for the specified group id """ result = self.conn.user.get(output='extend', usrgrpids=groupid) users = [user['alias'] for user in result] return users def create_group(self, group): """ Creates a new Zabbix group Args: group (str): The Zabbix group name to create Returns: The groupid of the newly created group """ result = self.conn.usergroup.create(name=group) groupid = result['usrgrpids'].pop() return groupid def create_user(self, user, groupid, user_opt): """ Creates a new Zabbix user Args: user (dict): A dict containing the user details groupid (int): The groupid for the new user user_opt (dict): User options """ random_passwd = ''.join( random.sample(string.ascii_letters + string.digits, 32)) user_defaults = { 'autologin': 0, 'type': 1, 'usrgrps': [{ 'usrgrpid': str(groupid) }], 'passwd': random_passwd } user_defaults.update(user_opt) user.update(user_defaults) result = self.conn.user.create(user) return result def delete_user(self, user): """ Deletes Zabbix user Args: user (string): Zabbix username """ userid = self.get_user_id(user) result = self.conn.user.delete(userid) return result def update_user(self, user, groupid): """ Adds an existing Zabbix user to a group Args: user (dict): A dict containing the user details groupid (int): The groupid to add the user to """ userid = self.get_user_id(user) if self.conn.api_version() >= "3.4": members = self.conn.usergroup.get(usrgrpids=[str(groupid)], selectUsers='extended') grpusers = members[0]['users'] userids = set() for u in grpusers: userids.add(u['userid']) userids.add(str(userid)) if not self.dryrun: result = self.conn.usergroup.update(usrgrpid=str(groupid), userids=list(userids)) else: if not self.dryrun: result = self.conn.usergroup.massadd(usrgrpids=[str(groupid)], userids=[str(userid)]) return result def update_media(self, user, description, sendto, media_opt): """ Adds media to an existing Zabbix user Args: user (dict): A dict containing the user details description (str): A string containing Zabbix media description sendto (str): A string containing address, phone number, etc... media_opt (dict): Media options """ userid = self.get_user_id(user) mediatypeid = self.get_mediatype_id(description) if mediatypeid: media_defaults = { 'mediatypeid': mediatypeid, 'sendto': sendto, 'active': '0', 'severity': '63', 'period': '1-7,00:00-24:00' } media_defaults.update(media_opt) if self.conn.api_version() >= "3.4": result = self.conn.user.update(userid=str(userid), user_medias=[media_defaults]) else: self.delete_media_by_description(user, description) result = self.conn.user.updatemedia(users=[{ "userid": str(userid) }], medias=media_defaults) else: result = None return result def delete_media_by_description(self, user, description): """ Remove all media from user (with specific mediatype) Args: user (dict): A dict containing the user details description (str): A string containing Zabbix media description """ userid = self.get_user_id(user) mediatypeid = self.get_mediatype_id(description) if mediatypeid: user_full = self.conn.user.get( output="extend", userids=userid, selectMedias=["mediatypeid", "mediaid"]) media_ids = [ int(u['mediaid']) for u in user_full[0]['medias'] if u['mediatypeid'] == mediatypeid ] if media_ids: self.logger.info( 'Remove other exist media from user %s (type=%s)' % (user, description)) for id in media_ids: self.conn.user.deletemedia(id) def create_missing_groups(self): """ Creates any missing LDAP groups in Zabbix """ missing_groups = set(self.ldap_groups) - set( [g['name'] for g in self.get_groups()]) for eachGroup in missing_groups: self.logger.info('Creating Zabbix group %s' % eachGroup) if not self.dryrun: grpid = self.create_group(eachGroup) self.logger.info('Group %s created with groupid %s' % (eachGroup, grpid)) def convert_severity(self, severity): converted_severity = severity.strip() if re.match("\d+", converted_severity): return converted_severity sev_entries = collections.OrderedDict({ "Disaster": "0", "High": "0", "Average": "0", "Warning": "0", "Information": "0", "Not Classified": "0", }) for sev in converted_severity.split(","): sev = sev.strip() if sev not in sev_entries: raise Exception("wrong argument: %s" % sev) sev_entries[sev] = "1" str_bitmask = "" for sev, digit in sev_entries.items(): str_bitmask += digit converted_severity = str(int(str_bitmask, 2)) self.logger.info('Converted severity "%s" to "%s"' % (severity, converted_severity)) return converted_severity def sync_users(self): """ Syncs Zabbix with LDAP users """ self.ldap_conn.connect() zabbix_all_users = self.get_users() # Lowercase list of user zabbix_all_users = [x.lower() for x in zabbix_all_users] for eachGroup in self.ldap_groups: ldap_users = self.ldap_conn.get_group_members(eachGroup) # Lowercase list of users ldap_users = {k.lower(): v for k, v in ldap_users.items()} # Do nothing if LDAP group contains no users and "--delete-orphans" is not specified if not ldap_users and not self.deleteorphans: continue zabbix_grpid = [ g['usrgrpid'] for g in self.get_groups() if g['name'] == eachGroup ].pop() zabbix_group_users = self.get_group_members(zabbix_grpid) missing_users = set(list( ldap_users.keys())) - set(zabbix_group_users) # Add missing users for eachUser in missing_users: # Create new user if it does not exists already if eachUser not in zabbix_all_users: self.logger.info( 'Creating user "%s", member of Zabbix group "%s"' % (eachUser, eachGroup)) user = {'alias': eachUser} if self.ldap_conn.get_user_givenName( ldap_users[eachUser]) is None: user['name'] = '' else: user['name'] = self.ldap_conn.get_user_givenName( ldap_users[eachUser]).decode('utf8') if self.ldap_conn.get_user_sn( ldap_users[eachUser]) is None: user['surname'] = '' else: user['surname'] = self.ldap_conn.get_user_sn( ldap_users[eachUser]).decode('utf8') if not self.dryrun: self.create_user(user, zabbix_grpid, self.user_opt) zabbix_all_users.append(eachUser) else: # Update existing user to be member of the group self.logger.info( 'Updating user "%s", adding to group "%s"' % (eachUser, eachGroup)) if not self.dryrun: self.update_user(eachUser, zabbix_grpid) # Handle any extra users in the groups extra_users = set(zabbix_group_users) - set(list( ldap_users.keys())) if extra_users: self.logger.info( 'Users in group %s which are not found in LDAP group:' % eachGroup) for eachUser in extra_users: if self.deleteorphans: self.logger.info('Deleting user: "******"' % eachUser) if not self.dryrun: self.delete_user(eachUser) else: self.logger.info('User not in ldap group "%s"' % eachUser) # update users media onlycreate = False media_opt_filtered = [] for elem in self.media_opt: if elem[0] == "onlycreate" and elem[1].lower() == "true": onlycreate = True elif elem[0] == "severity": media_opt_filtered.append( (elem[0], self.convert_severity(elem[1]))) else: media_opt_filtered.append(elem) if onlycreate: self.logger.info( "Add media only on newly created users for group >>>%s<<<" % eachGroup) zabbix_group_users = missing_users else: self.logger.info( "Update media on all users for group >>>%s<<<" % eachGroup) zabbix_group_users = self.get_group_members(zabbix_grpid) for eachUser in set(zabbix_group_users): eachUser = eachUser.lower() if self.ldap_media: self.logger.info( '>>> Updating/create user media for "%s", update "%s"' % (eachUser, self.media_description)) if self.ldap_conn.get_user_media(ldap_users[eachUser], self.ldap_media): sendto = self.ldap_conn.get_user_media( ldap_users[eachUser], self.ldap_media).decode("utf8") else: sendto = self.ldap_conn.get_user_media( ldap_users[eachUser], self.ldap_media) if sendto and not self.dryrun: self.update_media(eachUser, self.media_description, sendto, media_opt_filtered) else: self.logger.info( '>>> Ignoring media for "%s" because of configuration' % (eachUser)) self.ldap_conn.disconnect()
import sys, socket, time, re, datetime from pyzabbix import ZabbixAPI from difflib import Differ trigprevlist = [] triglist = [] counter = 0 try: zapi = ZabbixAPI(z_url) zapi.session.timeout = 5 zapi.login(z_user, z_pass) except Exception as e: print(e) exit(3) print ("Connected to Zabbix API Version %s" % zapi.api_version()) irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socket print("Establishing connection to [%s]" % (server)) irc.connect((server, 6667)) #connects to the server irc.setblocking(False) sock_auth = "USER "+ botuser +" "+ botuser +" "+ botuser +" :This is the Steinvord bot!\n" sock_nick = "NICK "+ botnick +"\n" sock_nicksrv = "PRIVMSG nickserv :iNOOPE\r\n" sock_join = "JOIN "+ channel +"\n" irc.send(sock_auth.encode(encoding)) irc.send(sock_nick.encode(encoding)) irc.send(sock_nicksrv.encode(encoding)) irc.send(sock_join.encode(encoding))
p.print_help() print "NOTE: Zabbix 1.8.0 doesn't check LDAP when authenticating." sys.exit(-1) def errmsg(msg): sys.stderr.write(msg + "\n") sys.exit(-1) if __name__ == "__main__": options, args = get_options() zapi = ZabbixAPI(server=options.server,log_level=3) try: zapi.login(options.username, options.password) print "Zabbix API Version: %s" % zapi.api_version() print "Logged in: %s" % str(zapi.test_login()) except ZabbixAPIException, e: sys.stderr.write(str(e) + '\n') try: for host in zapi.host.get(monitored_hosts=True, extendoutput=True): if host['dns'] == "": print "%s - %s - %s" % (host['host'], host['ip'], host['useip']) else: print "%s - %s - %s" % (host['dns'], host['ip'], host['useip']) if host['useip'] == "1" and host['dns'] != "": print "Updating %s to monitor by FQDN." % host['dns'] newhost = host newhost['useip'] = 0
def connectZabbix(region): zapi = ZabbixAPI("http://" + region[1], user=username, password=pas) print("Connected to %s Zabbix API Version %s" % (region[0], zapi.api_version())) return zapi
#!/bin/python from pyzabbix import ZabbixAPI import pandas as pd templateid = [] items = [] nometemplate = [] n = 1 user = str(raw_input("Digite o User: "******"Digite a senha: ")) zapi = ZabbixAPI('http://localhost/zabbix') zapi.login('Admin', 'zabbix') print(zapi.api_version()) for i in zapi.template.get(output='extend'): templateid.append(i['host']) for x in templateid: #print x for linha in zapi.template.get(selectItems={'items': 'name'}, filter={'name': x}): tam = len(linha['items']) #nometemplate.append(x) #items.append(linha['items']) for h in range(0, tam): nometemplate.append(x) items.append(linha['items'][h]['name']) #tam = len(linha['items'])
with open(filename, 'rb') as file: obj = pickle.load(file) return obj logw('Start.') if len(c.vuln_api_key) != 64: logw('Error: not a valid Vulners API-key.') exit(1) # создаем сессию в заббикс try: zapi = ZabbixAPI(c.zbx_url, timeout=10) zapi.session.verify = c.zbx_verify_ssl_certs zapi.login(c.zbx_user, c.zbx_pass) logw('Connected to Zabbix API v.{zapi_ver}'.format(zapi_ver=zapi.api_version())) except Exception as e: logw('Error: Can\'t connect to Zabbix API. Exception: {e}'.format(e=e)) exit(1) # Если матрица хостов есть - загружаем дамп с диска if os.path.exists(c.h_matrix_dumpfile): logw('Found a dump of the h_matrix in {h_matrix_dumpfile}. Loading.'.format(h_matrix_dumpfile=c.h_matrix_dumpfile)) h_matrix = dump_load(c.h_matrix_dumpfile) total_hosts = len(h_matrix) else: # если дампа матрицы на диске нет - формируем (исходные данные из zabbix и затем обогащаем их через vulners) total_hosts = 0 try: h_matrix = zapi.item.get(search={'key_': item_key}, monitored=True, output=['hostid']) full_hosts = len(h_matrix)
return obj logw('Start.') if len(c.vuln_api_key) != 64: logw('Error: not a valid Vulners API-key.') exit(1) # создаем сессию в заббикс try: zapi = ZabbixAPI(c.zbx_url, timeout=10) zapi.session.verify = c.zbx_verify_ssl_certs zapi.login(c.zbx_user, c.zbx_pass) # todo: checking that zabbix version >= 3.4 logw('Connected to Zabbix API v.{zapi_ver}'.format( zapi_ver=zapi.api_version())) except Exception as e: logw('Error: Can\'t connect to Zabbix API. Exception: {e}'.format(e=e)) exit(1) # Если матрица хостов есть - загружаем дамп с диска if os.path.exists(c.h_matrix_dumpfile): logw( 'Found a dump of the h_matrix in {h_matrix_dumpfile}. Loading.'.format( h_matrix_dumpfile=c.h_matrix_dumpfile)) h_matrix = dump_load(c.h_matrix_dumpfile) total_hosts = len(h_matrix) else: # если дампа матрицы на диске нет - формируем (исходные данные из zabbix и затем обогащаем их через vulners) total_hosts = 0 try:
class ZabbixConfig(object): def __init__(self, endpoint, user, password=''): self.zapi = ZabbixAPI(endpoint) self.zapi.login(user, password) print("Connected to Zabbix API Version %s" % self.zapi.api_version()) self.item_id = None self.trigger_id = None def create_action(self, sendto, web_url, use_zabbix_severity=False): use_console_link = True medias = self.zapi.mediatype.get(output='extend') try: media_id = [m for m in medias if m['description'] == 'Alerta'][0]['mediatypeid'] except Exception: print('media does not exist. creating...') response = self.zapi.mediatype.create( type=SCRIPT, description='Alerta', exec_path='zabbix-alerta', exec_params='{ALERT.SENDTO}\n{ALERT.SUBJECT}\n{ALERT.MESSAGE}\n', maxattempts='5', attempt_interval='5s' ) media_id = response['mediatypeids'][0] users = self.zapi.user.get(output='extend') admin_user_id = [u for u in users if u['alias'] == 'Admin'][0]['userid'] media_alerta = { 'mediatypeid': media_id, 'sendto': sendto, 'active': ENABLED, 'severity': NIWAHD, 'period': '1-7,00:00-24:00' } try: self.zapi.user.updatemedia( users={"userid": admin_user_id}, medias=media_alerta ) except ZabbixAPIException as e: sys.exit(e) default_message = ( "resource={HOST.NAME1}\r\n" "event={ITEM.KEY1}\r\n" "environment=Production\r\n" "severity={TRIGGER.SEVERITY}" + ("!!" if use_zabbix_severity else "") + "\r\n" "status={TRIGGER.STATUS}\r\n" "ack={EVENT.ACK.STATUS}\r\n" "service={TRIGGER.HOSTGROUP.NAME}\r\n" "group=Zabbix\r\n" "value={ITEM.VALUE1}\r\n" "text={TRIGGER.STATUS}: {TRIGGER.NAME}\r\n" "tags={EVENT.TAGS}\r\n" "attributes.ip={HOST.IP1}\r\n" "attributes.thresholdInfo={TRIGGER.TEMPLATE.NAME}: {TRIGGER.EXPRESSION}\r\n" "attributes.eventId={EVENT.ID}\r\n" "attributes.triggerId={TRIGGER.ID}\r\n" "type=zabbixAlert\r\n" "dateTime={EVENT.DATE}T{EVENT.TIME}Z\r\n" ) operations_console_link = 'attributes.moreInfo=<a href="%s/tr_events.php?triggerid={TRIGGER.ID}&eventid={EVENT.ID}" target="_blank">Zabbix console</a>' % web_url operations = { "operationtype": SEND_MESSAGE, "opmessage": { "default_msg": USE_DATA_FROM_OPERATION, "mediatypeid": media_id, "subject": "{TRIGGER.STATUS}: {TRIGGER.NAME}", "message": default_message + operations_console_link if use_console_link else '' }, "opmessage_usr": [ { "userid": admin_user_id } ] } recovery_console_link = 'attributes.moreInfo=<a href="%s/tr_events.php?triggerid={TRIGGER.ID}&eventid={EVENT.RECOVERY.ID}" target="_blank">Zabbix console</a>' % web_url recovery_operations = { "operationtype": SEND_MESSAGE, "opmessage": { "default_msg": USE_DATA_FROM_OPERATION, "mediatypeid": media_id, "subject": "{TRIGGER.STATUS}: {TRIGGER.NAME}", "message": default_message + recovery_console_link if use_console_link else '' }, "opmessage_usr": [ { "userid": admin_user_id } ] } try: self.zapi.action.create( name='Forward to Alerta', eventsource=TRIGGERS, status=ENABLED, esc_period=120, def_shortdata="{TRIGGER.NAME}: {TRIGGER.STATUS}", def_longdata=default_message, r_shortdata="{TRIGGER.NAME}: {TRIGGER.STATUS}", r_longdata=default_message, maintenance_mode=DO_NOT_PAUSE_EXEC, operations=[operations], recovery_operations=[recovery_operations] ) except ZabbixAPIException as e: print(e) def test_action(self, trapper, endpoint, key=None): hosts = self.zapi.host.get() zabbix_server_id = [h for h in hosts if h['name'] == 'Zabbix server'][0]['hostid'] # enable zabbix server monitoring self.zapi.host.update(hostid=zabbix_server_id, status=ENABLED) description = 'Test trigger event on {HOST.NAME}' try: response = self.zapi.item.create( name='Test Zabbix-Alerta Integration', type=ZABBIX_TRAPPER, key_='test.alerta', value_type=TEXT, hostid=zabbix_server_id, status=ENABLED ) self.item_id = response['itemids'][0] response = self.zapi.trigger.create( hostid=zabbix_server_id, description=description, expression='{Zabbix server:test.alerta.diff()}>0', type=GENERATE_MULTIPLE_EVENTS, priority=INFORMATION, status=ENABLED, manual_close=ALLOW_MANUAL_CLOSE ) self.trigger_id = response['triggerids'][0] except ZabbixAPIException: triggers = self.zapi.trigger.get(hostids=zabbix_server_id) self.trigger_id = [t for t in triggers if t['description'] == description][0]['triggerid'] self.item_id = self.zapi.item.get(triggerids=self.trigger_id)[0]['itemid'] def zabbix_send(value): cfg = protobix.ZabbixAgentConfig() cfg.server_active = trapper zbx = protobix.DataContainer(cfg) zbx.data_type = 'items' zbx.add_item(host='Zabbix server', key='test.alerta', value=value) response = zbx.send() print(response) print('sending test items') now = int(time.time()) zabbix_send('OK') print('wait for items to be received') count = 0 while True: count += 1 response = self.zapi.history.get(itemids=[self.item_id], history=TEXT, time_from=now, output='extend', sortfield='clock', sortorder='DESC', limit=10) zabbix_send('RETRY%s' % count) if len(response) > 1: break print('waiting 5 seconds...') time.sleep(5) print('sent items received by zabbix') print(response) from_date = datetime.utcnow().replace(microsecond=0).isoformat() + ".000Z" print('wait for triggered event') while True: response = self.zapi.event.get(objectids=self.trigger_id, time_from=now, output='extend', sortfield=['clock', 'eventid'], sortorder='DESC') if len(response) > 0 and 'eventid' in response[0]: event_id = response[0]['eventid'] break print('waiting 2 seconds...') time.sleep(2) print('event triggered') print(response[0]) print('wait for alert') while True: response = self.zapi.alert.get(eventid=event_id, time_from=now, output='extend',) if len(response) > 0: break print('waiting 2 seconds...') time.sleep(2) print('alert triggered by event') print(response[0]) api = Client(endpoint, key) print('check alert received by Alerta') while True: try: response = api.get_alerts(query=[('event', 'test.alerta'), ('from-date', from_date)]) except Exception as e: sys.exit(e) if len(response) > 0: break time.sleep(5) print(response[0].last_receive_id) print('success!') def clean_up(self): try: self.zapi.trigger.delete(self.trigger_id) self.zapi.item.delete(self.item_id) except ZabbixAPIException: pass
def connect_to_host(host, user, password): print "Connecting to " + host api = ZabbixAPI(host) api.login(user, password) print("Connected to Zabbix API Version %s" % api.api_version()) return api
class ZabbixAgent(object): def __init__(self, url, login, password): self.url = url self.login = login self.password = password self.zbx_api = ZabbixAPI(url=url, use_authenticate=False, user=login, password=password) log.debug('Object ZabbixAgent created') log.debug('API ver. %s', self.api_ver()) def get_item_data(self, hostname, item): reply = self.zbx_api.host.get(filter={'name': hostname}, output='shorten') if not reply: raise ZbxException("hostname: {} not found".format(hostname)) hostid = reply[0]['hostid'] log.debug('hostID %s', hostid) item_data = self.zbx_api.item.get(filter={'hostid': hostid, 'key_': item}, output=['lastvalue']) log.debug('itemID %s', hostid) if not item_data: raise ZbxException('item: {} not found'.format(item)) if len(item_data) > 1: raise ZbxException('return items expected one item') return int(item_data[0]['lastvalue']) def get_item_data2(self, hostname, item_in, item_out): reply = self.zbx_api.host.get(filter={'name': hostname}, output='shorten') if not reply: raise ZbxException("hostname: {} not found".format(hostname)) hostid = reply[0]['hostid'] log.debug('hostID %s', hostid) if '+' in item_in: item_in_split = list(map(str.strip, item_in.split('+'))) item_in_data = self.zbx_api.item.get(filter={'hostid': hostid, 'key_': item_in_split[0]}, output=['lastvalue']) for item_in_elem in item_in_split[1:]: item_in_data[0]['lastvalue'] = str(int(item_in_data[0]['lastvalue']) + int(self.zbx_api.item.get(filter={'hostid': hostid, 'key_': item_in_elem}, output=['lastvalue'])[0]['lastvalue'])) else: item_in_data = self.zbx_api.item.get(filter={'hostid': hostid, 'key_': item_in}, output=['lastvalue']) log.debug('itemID %s', hostid) if not item_in_data: raise ZbxException('item: {} not found'.format(item_in)) if '+' in item_out: item_out_split = list(map(str.strip, item_out.split('+'))) item_out_data = self.zbx_api.item.get(filter={'hostid': hostid, 'key_': item_out_split[0]}, output=['lastvalue']) for item_out_elem in item_out_split[1:]: item_out_data[0]['lastvalue'] = str(int(item_out_data[0]['lastvalue']) + int(self.zbx_api.item.get(filter={'hostid': hostid, 'key_': item_out_elem}, output=['lastvalue'])[0]['lastvalue'])) else: item_out_data = self.zbx_api.item.get(filter={'hostid': hostid, 'key_': item_out}, output=['lastvalue']) log.debug('itemID %s', hostid) if not item_in_data: raise ZbxException('item: {} not found'.format(item_out)) if len(item_in_data) > 1: raise ZbxException('return items expected one item: {}'.format(item_in_data)) if len(item_out_data) > 1: raise ZbxException('return items expected one item: {}'.format(item_out_data)) return int(item_in_data[0]['lastvalue']), int(item_out_data[0]['lastvalue']) def api_ver(self): return self.zbx_api.api_version() def scan_map(self, map_name): map_data = self.zbx_api.map.get(filter={'name': map_name}, selectSelements=['elements', 'selementid', 'elementtype', 'iconid_off', 'x', 'y'], selectLinks=['selementid1', 'selementid2', 'linkid'] ) if not map_data: raise ZbxException('map: {} not found'.format(map_name)) if len(map_data) > 1: raise ZbxException('return maps expected one map') return map_data[0] def scan_map_all(self): maps_data = self.zbx_api.map.get(selectSelements=['elementid', 'selementid', 'elementtype', 'iconid_off', 'x', 'y'], selectLinks=['selementid1', 'selementid2', 'linkid']) if not maps_data: raise ZbxException('maps not found') if len(maps_data) > 1: raise ZbxException('return maps expected one map') return maps_data def get_hostname(self, hostid): hostname = self.zbx_api.host.get(hostids=hostid, output=['host']) if not hostname: raise ZbxException('hostname not found') if len(hostname) > 1: raise ZbxException('return hostnames expected one hostname') return hostname[0]['host'] def get_mapname(self, mapid): mapname = self.zbx_api.map.get(sysmapids=mapid, output=['name']) if not mapname: raise ZbxException('map name not found') if len(mapname) > 1: raise ZbxException('return map names expected one map name') return mapname[0]['name'] def get_triggername(self, triggerid): triggername = self.zbx_api.trigger.get(triggerid=triggerid, output=['description']) if not triggername: raise ZbxException('trigger name not found') if len(triggername) > 1: raise ZbxException('return trigger names expected one trigger name') return triggername[0]['description'] def get_hostgroupname(self, groupid): hostgroupname = self.zbx_api.hostgroup.get(groupids=groupid, output=['name']) if not hostgroupname: raise ZbxException('hostgroup name not found') if len(hostgroupname) > 1: raise ZbxException('return hostgroup names expected one hostgroup name') return hostgroupname[0]['name'] def get_imagename(self, imageid): imagename = self.zbx_api.image.get(imageids=imageid, output=['name']) if not imagename: raise ZbxException('image name not found') if len(imagename) > 1: raise ZbxException('return image names expected one image name') return imagename[0]['name'] def image_to_zabbix(self, pathfn, zbx_img_name): with open(pathfn, 'rb') as img: b64img = base64.b64encode(img.read()).decode() image_data = self.zbx_api.image.get(filter={'name': zbx_img_name}) if not image_data: self.zbx_api.image.create(name=zbx_img_name, imagetype=2, image=b64img) else: self.zbx_api.image.update(imageid=image_data[0]['imageid'], image=b64img) def image_get(self, imageid): image_data = self.zbx_api.image.get(imageids=imageid, select_image=True) return image_data[0]['image']
#print "NEW_EPOCH: %s" % new_epoch #GET LOCAL CONFIGURATION config = get_config("zdh.conf") server={} server['url'] = config.get('server','url') server['user'] = config.get('server','user') server['password'] = config.get('server','password') logger.debug("server = '%s'" % server) #LOGIN TO ZABBIX zapi = ZabbixAPI(server['url']) zapi.login(server['user'],server['password']) logger.debug("connected to Zabbix API Version %s" % zapi.api_version()) found_host=False for h in zapi.host.get(filter={"host": host_name}, output="extend"): if (h['host'] == host_name): found_host=True host_id = h['hostid'] host_status = h['status'] #msg = "host %s (%s) status is '%s'" % (h['host'],h['hostid'],h['status']) if (host_status == "1"): host_status_text = "disabled" if (host_status == "0"): host_status_text = "enabled" #logger.info("host_status_text: %s",host_status_text)
#!/bin/python from pyzabbix import ZabbixAPI zapi = ZabbixAPI('http://localhost/zabbix') zapi.login('Admin', 'zabbix') print('Connected to Zabbix API Version %s' % zapi.api_version() + '\n') # Get a list of all issues (AKA tripped triggers) triggers = zapi.trigger.get( only_true=1, skipDependent=1, monitored=1, active=1, output='extend', expandDescription=1, selectHosts=['host'], ) # Do another query to find out which issues are Unacknowledged unack_triggers = zapi.trigger.get( only_true=1, skipDependent=1, monitored=1, active=1, output='extend', expandDescription=1, selectHosts=['host'], withLastEventUnacknowledged=1, ) unack_trigger_ids = [t['triggerid'] for t in unack_triggers] for t in triggers:
'%(asctime)s %(process)d %(levelname)s %(message)s [%(filename)s:%(lineno)d]' ) triggered_host = sys.argv[1] trigger_id = sys.argv[2] event_id = sys.argv[3] logging.info( 'Getting Started with the event: {}/tr_events.php?triggerid={}&eventid={}'. format(zbx_url, trigger_id, event_id)) try: zapi = ZabbixAPI(zbx_url, timeout=10) zapi.session.verify = zbx_verify_ssl zapi.login(zbx_user, zbx_pass) logging.info('Connected to Zabbix API v.{}'.format(zapi.api_version())) except Exception as e: logging.info( 'Error: Can\'t connect to Zabbix API. Exception: {}'.format(e)) exit(1) # todo: добавить обработку "закытие события, без выполнения действия" try: ack = zapi.event.get(eventids=event_id, select_acknowledges=['alias', 'message'], output=['alias', 'message']) ack_alias = ack[0]['acknowledges'][0]['alias'] if ack_alias not in acknowledge_users: logging.info( 'Not trusted user in acknowledge: {}. Skipping this request to fix.' .format(ack_alias))
priority='0', comments=trig_proto_comm, status='0') print('Created host "{}" (id: {})\n'.format(zbx_vname, host_id)) return host_id except Exception as e: print('Can\'t create host {}. Exception: {}'.format(zbx_host, e)) exit(1) if not len(sys.argv) > 1: print('\nYou do not specify the objects that you want to create.\nShow help: ./prepare.py -h\nTypical use: ./prepare.py -uvtda') exit(0) try: zapi = ZabbixAPI(zbx_url, timeout=5) zapi.session.verify = zbx_verify_ssl zapi.login(zbx_user, zbx_pass) zapi_ver = zapi.api_version() print('Connected to Zabbix API v.{}\n'.format(zapi.api_version())) zapi_ver_float = float(zapi_ver.split('.')[0] + '.' + zapi_ver.split('.')[1]) if zapi_ver_float < required_zapi_ver: print('Required Zabbix version {} or higher\nExit.'.format(required_zapi_ver)) exit(0) except Exception as e: print('Error: Can\'t connect to Zabbix API. Exception: {}'.format(e)) exit(1) host_use_ip = 1 # CHECK Z-UTILS if args.utils:
def main(): global z #try: # opts, args = getopt.getopt(argv,"hp:s:u:",["password="******"server=", "user="******"cli-inventory.py -s -server= <server> -u -username= <username> -p -password= <password>") # sys.exit(2) #for opt, arg in opts: # if opt == '-h': # print("cli-inventory.py -s -server= <server> -u -username= <username> -p -password= <password>") # sys.exit() # elif opt in ("-s", "-server="): # serverip = arg # elif opt in ("-u", "-username="******"-p", "-password="******"Logged into ZabbixAPI version " + z.api_version()) except ZabbixAPIException as e: print(e, "\nProgram will now close.") sys.exit(2) except requests.Timeout as f: print(f, "\nProgram will now close.") sys.exit(2) else: print( "Must enter a correct URL for the Zabbix server (eg. http://192.168.0.4/zabbix)." ) sys.exit(2) else: print("Required parameter missing.") sys.exit(2) if filepath is not None: return filepath else: return 'arbitrary'
return triggers #--------------------------------------------------------------------------------------------------------------------- def checkGroups(hostgroup): hostgroup = hostgroup[:-1] groups = zapi.hostgroup.get(output='extend') groupids = [] for i in range(len(groups)): if hostgroup not in groups[i]['name']: continue else: groupids.append(groups[i]['groupid']) return groupids #--------------------------------------------------------------------------------------------------------------------- zapi = ZabbixAPI("http://zabbix_ip/zabbix/api_jsonrpc.php") zapi.login("zabbix_user", "zabbix_password") print("Connected to Zabbix API Version %s" % zapi.api_version()) time_till = time.mktime(datetime.now().timetuple()) time_from = time_till - 60 * 60 * 2 # 2 hours #---------------------------------------------------------# if time_from_arg == 0: # time_from = time_till - 60 * 60 * 2 # else: # time_from = time_till - time_from_arg # if time_till_arg > 0: # time_till = time_till - time_till_arg # #---------------------------------------------------------# if "*" in hostgroup: groupids = checkGroups(hostgroup) triggers = getTriggers() tot = len(triggers)
debug_print('Creating graph: %s' % graph_name) zabbix.graph.create(graph) except ZabbixAPIException as e: print >> sys.stderr, 'ZabbixAPIException thrown on graph: %s' % graph_name traceback.print_exc() ##################################################################################################### # main ##################################################################################################### ## connect to Zabbix API ## zabbix = ZabbixAPI(zabbix_url) zabbix.login(zabbix_user, zabbix_password) debug_print('Connected to Zabbix API Version %s' % zabbix.api_version()) for cluster in clusters: zabbix_items = {} # item_key -> (itemid, item_name) debug_print('Searching Zabbix items of node %s' % cluster) items = zabbix.item.getObjects(host=cluster) if not items: print 'WARNING: Cannot find items of Storwize node %s in Zabbix. Check Storwize node name and check Zabbix API user permissions to administer node %s in Zabbix.' % (cluster, cluster) for i in items: if ('key_' in i) and ('itemid' in i) and ('name' in i): zabbix_items[ i['key_'] ] = ( i['itemid'], i['name'] ) items = None