Example #1
0
    def test_login(self):
        httpretty.register_uri(
            httpretty.POST,
            "http://example.com/api_jsonrpc.php",
            body=json.dumps({
                "jsonrpc": "2.0",
                "result": "0424bd59b807674191e7d77572075f33",
                "id": 0
            }),
        )

        zapi = ZabbixAPI('http://example.com')
        zapi.login('mylogin', 'mypass')

        # Check request
        self.assertEqual(
            httpretty.last_request().body,
            json.dumps({
                'jsonrpc': '2.0',
                'method': 'user.login',
                'params': {'user': '******', 'password': '******'},
                'id': 0,
            })
        )
        self.assertEqual(
            httpretty.last_request().headers['content-type'],
            'application/json-rpc'
        )
        self.assertEqual(
            httpretty.last_request().headers['user-agent'],
            'python/pyzabbix'
        )

        # Check response
        self.assertEqual(zapi.auth, "0424bd59b807674191e7d77572075f33")
Example #2
0
    def test_host_get(self):
        httpretty.register_uri(
            httpretty.POST,
            "http://example.com/api_jsonrpc.php",
            body=json.dumps({
                "jsonrpc": "2.0",
                "result": [{"hostid": 1234}],
                "id": 0
            }),
        )

        zapi = ZabbixAPI('http://example.com')
        zapi.auth = "123"
        result = zapi.host.get()

        # Check request
        self.assertEqual(
            httpretty.last_request().body,
            json.dumps({
                'jsonrpc': '2.0',
                'method': 'host.get',
                'params': {},
                'auth': '123',
                'id': 0,
            })
        )

        # Check response
        self.assertEqual(result, [{"hostid": 1234}])
Example #3
0
    def test_host_delete(self):
        httpretty.register_uri(
            httpretty.POST,
            "http://example.com/api_jsonrpc.php",
            body=json.dumps({
                "jsonrpc": "2.0",
                "result": {
                    "itemids": [
                        "22982",
                        "22986"
                    ]
                },
                "id": 0
            }),
        )

        zapi = ZabbixAPI('http://example.com')
        zapi.auth = "123"
        result = zapi.host.delete("22982", "22986")

        # Check request
        self.assertEqual(
            httpretty.last_request().body,
            json.dumps({
                'jsonrpc': '2.0',
                'method': 'host.delete',
                'params': ["22982", "22986"],
                'auth': '123',
                'id': 0,
            })
        )

        # Check response
        self.assertEqual(set(result["itemids"]), set(["22982", "22986"]))
Example #4
0
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)
def client(**kwargs):
    global zapi
    if not zapi:
        zapi = ZabbixAPI(kwargs['url'])
        zapi.login(kwargs['username'], kwargs['password'])
        print zapi.api_version()
    return zapi
Example #6
0
class process_base(object):

    def __init__(self):
        ZABBIX_SERVER = 'http://192.168.1.203:82'
        #ZABBIX_SERVER = 'http://119.79.232.99:82'
        self.zapi = ZabbixAPI(ZABBIX_SERVER)
        # Login to the Zabbix API
        self.zapi.login('Admin', 'zabbix')
        self.zabbix_url = ZABBIX_SERVER

    def gid_2_group_list(self):
        '''
        '''
        return self.zapi.hostgroup.get(output='extend')

    def zabbix_url(self):
        # just for view.py intial the zabbix_url
        return self.zabbix_url

    def clock_2_time(self, clock_time):
        '''
        '''
        return datetime.fromtimestamp(int(clock_time)).strftime('%Y-%m-%d %X')

    def clock_2_timedelta(self, clock_time):
        '''

        '''
        time_delta = datetime.fromtimestamp(
            int(clock_time)) - datetime.fromtimestamp(0)
        delta_day = time_delta.days
        delta_hour = time_delta.seconds / 3600
        delta_min = time_delta.seconds % 3600 / 60
        return '%s days, %s hours, %s minutes' % (delta_day, delta_hour, delta_min)
def main(argv):

    cfgfile = "/etc/zabbix_stats.cfg"
    try:
        opts, args = getopt.getopt(argv, "hc:", ["configfile="])
    except getopt.GetoptError:
        print 'zabbix_stats.py -c <configfile>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'zabbix_stats.py -c <configfile>'
            sys.exit(2)
        elif opt in ("-c", "--configfile"):
            cfgfile = arg

    global pp
    pp = pprint.PrettyPrinter(indent=4)
    config = ConfigParser.ConfigParser()
    config.read(cfgfile)

    global zapi
    zapi = ZabbixAPI(config.get('Server', 'zabbixurl'))
    zapi.session.verify = False
    # Login to the Zabbix API
    zapi.login(config.get('Server', 'username'), config.get('Server', 'password'))

    while(1):
        Alerts()    
Example #8
0
File: zabbix.py Project: orviz/z2g
class ZabbixUtils(object):
    def __init__(self):
        s = requests.Session()
        s.auth = (CONF.zabbix.username, CONF.zabbix.password)
        s.verify = False

        self.zapi = ZabbixAPI(CONF.zabbix.url, s)
        self.zapi.login(CONF.zabbix.username, CONF.zabbix.password)

    def set_graphite_format(self, s):
        """
        Removes whitespaces and lowercases the string
        """
        return ''.join(s.split()).lower()

    def get_hosts_per_hostgroup(self):
        """Returns a dictionary with Zabbix's hostgroup->hosts mapping."""
        d = {}
        for hostgroup in self.zapi.hostgroup.get(real_hosts=1, 
                                                 output="extend",
                                                 selectHosts="extend"):
            name = hostgroup["name"]
            hosts = [host["name"] for host in hostgroup["hosts"]]
            d[name] = hosts
        return d

    def get_items_by_host(self, h, filters=[]):
        """Returns a formated list of (metric, value) pairs.

            h: Zabbix's name for the host.
            filters: a list of keys to search for.
        """
        d = {}
        for f in filters:
            for item in self.zapi.item.get(search={"key_": f},
                                      host=h, 
                                      output=["itemid",
                                              "name", 
                                              "lastvalue", 
                                              "key_"]):
                itemid = item.pop("itemid")
                d[itemid] = item

        l = []
        for m in d.values():
            l.append([m["key_"], m["lastvalue"]])

        l_metric = []
        hostgroups = [group["name"] for group in self.zapi.host.get(
                                            search={"name": h},
                                            output="groups", 
                                            selectGroups="extend")[0]["groups"]]
        h = self.set_graphite_format(h)
        for hgroup in hostgroups:
            hgroup = self.set_graphite_format(hgroup)
            for m in l:
                k = self.set_graphite_format(m[0])
                l_metric.append([".".join([hgroup, h, k]), m[1]])

        return l_metric
Example #9
0
def initiate_connection():
    global connection
    logger.error('Initiating connection')
    login = settings.ZABBIX_USER
    passwd = settings.ZABBIX_PASSWORD
    connection = ZabbixAPI(server=settings.ZABBIX_URL)
    connection.login(login, passwd)
def check_cluster(trigger):
    zapi = ZabbixAPI(zabbix_site)
    zapi.login(zabbix_user,zabbix_pass)
    
    trigger_notok = zapi.trigger.get(monitored=1,selectHosts=1,
                                     output=['hosts'],withLastEventUnacknowledged=1,
                                     search={'description':trigger},filter={"value":1})

    trigger_host_list = []
    for trigger_item in trigger_notok:
        trigger_host = trigger_item['hosts'][0]['hostid']
        trigger_host_list.append(int(trigger_host))

    trigger_host_msglist = []
    trigger_host_list_nondup = list(set(trigger_host_list))
    for trigger_host_nondup in trigger_host_list_nondup:
        trigger_host_dict = zapi.host.get(hostids=trigger_host_nondup)
        trigger_host_name = trigger_host_dict[0]['host']
        trigger_host_count = trigger_host_list.count(trigger_host_nondup)
        trigger_host_msg = "{0} trigger(s) on {1}".format(trigger_host_count,trigger_host_name)
        trigger_host_msglist.append(trigger_host_msg)

    if not trigger_host_msglist:
        print "OK"
    else:
        print '; '.join(trigger_host_msglist)

    return True
Example #11
0
    def _connect(self):
        s = requests.Session()
        s.auth = (CONF.zabbix.username, CONF.zabbix.password)
        s.verify = False
        conn = ZabbixAPI(CONF.zabbix.url, s)
        conn.login(CONF.zabbix.username, CONF.zabbix.password)

        return conn
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 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 get_zabbix_api():
    zapi = None
    if zabbix_comment_update:
        zapi = ZabbixAPI(zabbix_url)
        try:
            zapi.login(zabbix_user, zabbix_password)
        except Exception as e:
            print 'some errors occurs'
            print e
    return zapi
Example #15
0
class ZabbixClinet(object):
    def __init__(self, idc, address, username, password):
        self.idc = idc
        self.address = address
        try:
            self.zbx_api = ZabbixAPI(address)
            self.zbx_api.login(username, password)
        except Exception, error:
            # logging.warning(error)
            raise Exception
Example #16
0
def _get_zabbix(server = None, password = None, user = None):
    from pyzabbix import ZabbixAPI
    import thoth.zabbix as zabbix
    zabbix_server = server if server else os.environ.get('ZABBIX_SERVER', 'http://127.0.0.1')
    zabbix_user = user if user else os.environ.get('ZABBIX_USER', 'Admin')
    zabbix_password = password if password else os.environ.get('ZABBIX_PASSWORD', 'zabbix')
    if zabbix_server and not match('^http[s]*://', zabbix_server):
        zabbix_server = 'http://' + zabbix_server
    zbx = ZabbixAPI(zabbix_server)
    zbx.login(zabbix_user, zabbix_password)
    return zabbix.MonitorZabbix(zbx)
def disable_on_zabbix(instance_name):
    zapi = ZabbixAPI(zabbix_api)
    zapi.login(zabbix_user, zabbix_pass)

    hosts = zapi.host.get(filter={
        "name": instance_name
    })
    if len(hosts) > 0 and 'hostid' in hosts[0]:
        hostid = hosts[0]['hostid']
        print("Disabling on Zabbix: %s %s" %
              (instance_name, hostid))
        zapi.host.update(hostid=hostid, status=1)
def create_web_scenario(self,name,url,group,hostid,applicationid, url_name='Homepage',status='200'):
  request = ZabbixAPI.do_request(self, 'webcheck.get', params={ "filter": {"name": name}})
  if request['result']:
    print('Host "%s" already registered' % name)
    sys.exit(1)
  else:
    try:
      ZabbixAPI.do_request(self, 'webcheck.create',params={"name": name,"hostid": hostid,"applicationid": applicationid, "delay": '60',"retries": '3', "steps": [ { 'name': url_name, 'url': url,'status_codes': status, 'no': '1'} ] } )
      triggers = create_trigger(auth,name,url,group)
    except Exception, e:
      print(e)
      sys.exit(1)
Example #19
0
def wshtest():
    # The hostname at which the Zabbix web interface is available
    ZABBIX_SERVER = 'http://192.168.100.252:8001/zabbix/'
    
    zapi = ZabbixAPI(ZABBIX_SERVER)
    zapi.login('Admin', 'zabbix')
    host_name = '192.168.100.240'
    itemlist = zapi.item.get(output=["name","key_"], hostids=["10109"],filter={}, applicationids="566" )
    historylist = zapi.history.get(output="extend",history="3",itemids=["24670"],limit="100")
    data_timeline = ",".join([ x['clock'] for x in historylist ])
    value_line = ",".join([x['value'] for x in historylist])
    return data_timeline,value_line
    def sample(self):
        zapi = ZabbixAPI("http://zabbix.tonyrogers.me/zabbix/")
        zapi.session.verify = False
        zapi.login("Admin", "zabbix")
        ret = zapi.item.get(output=['lastvalue'],filter={'host':'zabbix.tonyrogers.me'},search={'key_':'zabbix[wcache,values]'})

        self.items.append({'x': self.seedX,
                           'y': ret[0]['lastvalue']})
        self.seedX += 1
        if len(self.items) > 10:
            self.items.popleft()
        return {'points': list(self.items)}
def authentication(server_url,user,password):

  if server_url and user and password:
    ZABBIX_SERVER = server_url
    zapi = ZabbixAPI(ZABBIX_SERVER)
    try:
      # Login to the Zabbix API
      zapi.login(user,password)
      return zapi
    except Exception, e:
      print(e)
      sys.exit(1)
Example #22
0
    def set_zabbix_handle(self, name, host, user, password, ssl_verify):
        if not self.zabbix_handles.get(name, False):
            zapi = ZabbixAPI(host)
            zapi.session.verify = ssl_verify
            zapi.login(user, password)

            self.Server.create(host=host, token=zapi.auth)
            self.zabbix_handles[name] = zapi
            ret = zapi
        else:
            ret = self.zabbix_handles[host]
        return ret
def get_zabbix_client(url, user, passwd, verify):
    """
    
    :param url: Zabbix API url  
    :param user: Zabbix API user
    :param passwd: Zabbix API password
    :param verify: Whether or not to verify the SSL certificate
    :return: ZABBIX API Client
    """
    z_client = ZabbixAPI(url)
    z_client.session.verify = verify
    z_client.login(user, passwd)
    return z_client
Example #24
0
def loginzabbix():
    try:
        config = ConfigParser.ConfigParser()
        config.read("zabbixmagic.ini")
        ZABBIX_SERVER = config.get("zabbixserver", "server")
        ZABBIX_USER = config.get("zabbixserver", "user")
        ZABBIX_PASS = config.get("zabbixserver", "password")
        global zapi
        zapi = ZabbixAPI(ZABBIX_SERVER)
        zapi.login(ZABBIX_USER, ZABBIX_PASS)
    except:
        print "Could'n connect to zabbix. Please check if URL " + ZABBIX_SERVER + " is available"
        exit(1)
 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 get_zapi(host, user, password, verify):
    """

    :param host:
    :param user:
    :param password:
    :param verify:
    :return:
    """
    zapi = ZabbixAPI(host)
    # Whether or not to verify the SSL certificate
    zapi.session.verify = verify
    zapi.login(user, password)
    return zapi
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 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'
Example #29
0
 def __init__(self, url, user, password):
     self.url = url
     self.user = user
     self.password = password
     self.client = ZabbixAPI(url=url, user=user, password=password)
Example #30
0
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_name = config.media_name
        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(self.__class__.__name__)

    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, name):
        """
        Retrieves the mediatypeid by name

        Args:
            name (str): Zabbix media type name

        Returns:
            The mediatypeid for specified media type name

        """
        result = self.conn.mediatype.get(filter={'name': name.strip()})

        if len(result) != 1:
            raise Exception(
                f"Ambiguous media found, {len(result)} different medias")

        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,
            'usrgrps': [{
                'usrgrpid': str(groupid)
            }],
            'passwd': random_passwd
        }

        if self.conn.api_version() >= "5.2":
            user_defaults['roleid'] = 1
        else:
            user_defaults['type'] = 1

        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)

            for unwanted_attrib in ["description", "name", "onlycreate"]:
                if unwanted_attrib in media_defaults:
                    del media_defaults[unwanted_attrib]

            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
                if 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()
                ldap_user = ldap_users.get(eachUser, None)
                if not ldap_user:
                    continue
                if self.ldap_media:
                    self.logger.info(
                        '>>> Updating/create user media for "%s", update "%s"'
                        % (eachUser, self.media_name))
                    if self.ldap_conn.get_user_media(ldap_user,
                                                     self.ldap_media):
                        sendto = self.ldap_conn.get_user_media(
                            ldap_user, self.ldap_media).decode("utf8")
                    else:
                        sendto = self.ldap_conn.get_user_media(
                            ldap_user, self.ldap_media)

                    if sendto and not self.dryrun:
                        self.update_media(eachUser, self.media_name, sendto,
                                          media_opt_filtered)
                else:
                    self.logger.info(
                        '>>> Ignoring media for "%s" because of configuration'
                        % (eachUser))

        self.ldap_conn.disconnect()
Example #31
0
"""zabbix:host be added groups ;host be removed groups ; get the relationship between user,usergroup,hostgroup """

from pyzabbix import ZabbixAPI
import setting
print(setting.zURL)
"""zapi is  global variable"""
zabbix_url =
username, passwd =
zapi = ZabbixAPI(zabbix_url)
zapi.login(username, passwd)

class Objzabbix(object):
    def __init__(self):
        pass

    def getHostID(self,hosts=[]):
        pass
    def getGroupID(self,group=''):
        pass
    def addGroup(self,hosts=[],group=''):
        pass
    def removeGroup(self):
        pass
    def getUserGroup(self):
        pass

Example #32
0
#!/usr/bin/env python
"""
Looks up a host based on its name, and then adds an item to it
"""

from pyzabbix import ZabbixAPI, ZabbixAPIException
import sys
import os

# The hostname at which the Zabbix web interface is available
# Replace with url to interface. Keep the quotes.
ZABBIX_SERVER = 'Zabbix Web Interface URL'

zapi = ZabbixAPI(ZABBIX_SERVER)

# Login to the Zabbix API
#replace username and password with the appropriate data. Keep the quotes around the data.
zapi.login('username', 'password')

command = "./zhostfinder.py -e -A"
os.system(command)

hostID = raw_input("What host ID will we be using:")

#Delete the host from the console
hosts = zapi.host.delete((hostID))
Example #33
0
 def login(self):
     self.client = ZabbixAPI(self.zab_host)
     self.client.login(self.zab_user, self.zab_pwd)
     self.botoclient = boto3.client('ec2')
Example #34
0

def dump_load(filename):
    with open(filename, 'rb') as file:
        obj = pickle.load(file)
    return obj


logging.info('Start.')
if len(vuln_api_key) != 64:
    logging.error('Error: not a valid Vulners API-key')
    exit(1)

# создаем сессию в заббикс
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.error(
        'Error: Can\'t connect to Zabbix API. Exception: {}'.format(e))
    exit(1)

# Если матрица хостов есть - загружаем дамп с диска
if os.path.exists(h_matrix_dumpfile):
    logging.info('Found a dump of the h_matrix in {}. Loading'.format(
        h_matrix_dumpfile))
    h_matrix = dump_load(h_matrix_dumpfile)
    total_hosts = len(h_matrix)
else:
Example #35
0
#!/usr/bin/env python
#coding:utf-8
#create_time: 2017/3/29
#author:sailq
import ast
from pyzabbix import ZabbixAPI
zapi = ZabbixAPI("http://domain")
zapi.login("user","passwd")
import MySQLdb
#建立一个连接
conn=MySQLdb.connect(host='host',user='******',passwd='passwd',db='dbname',port=3306)
#建立一个游标
cur =conn.cursor()
#根据group_name创建分组
def create_new_group(group_name):
    try:
        new=zapi.hostgroup.create(name=group_name)
        return new
    except Exception as e:
        pass
    #return new
#获取标准的host_name(ip)
def get_host():
    list = []
    remove_host_list=['192.168.100.1-H3C-5500','192.168.100.10-H3C-5500','192.168.100.3-H3C-5500','192.168.100.4-H3C-5500','192.168.100.2-H3C-5500','192.168.100.250-H3C-5800-Cluster','192.168.100.5-H3C-5500','192.168.100.6-H3C-5500','192.168.100.8-H3C-5500','172.16.21.45-H3C-5500','windows-WIN-2DKKICHMD6H']
    host = zapi.host.get()
    for i in host:
        list.append(i['name'])
    for d_host in remove_host_list:
        if d_host in list:
            list.remove(d_host)
Example #36
0
#!/usr/bin/python
from pyzabbix import ZabbixAPI
import array

URL_ZABBIX = ""
USER_ZABBIX = ""
PASSWORD_ZABBIX = ""

# Fazendo login
zapi = ZabbixAPI(URL_ZABBIX)
zapi.login(USER_ZABBIX, PASSWORD_ZABBIX)

# Coletando todos hosts e seus respectivos status
hosts_dis = zapi.host.get(output=["name", "status"])

# For nos hosts e verifica o status (disable = 1)
for host in hosts_dis:
    status = int(host['status'])
    if (status == 1):
        print host['name']
Example #37
0
"""
Import Zabbix XML templates
"""

from pyzabbix import ZabbixAPI, ZabbixAPIException
import glob

# The hostname at which the Zabbix web interface is available
ZABBIX_SERVER = 'https://zabbix.example.com'

zapi = ZabbixAPI(ZABBIX_SERVER)

# Login to the Zabbix API
zapi.login("admin", "zabbix")

rules = {
    'applications': {
        'createMissing': 'true',
        'updateExisting': 'true'
    },
    'discoveryRules': {
        'createMissing': 'true',
        'updateExisting': 'true'
    },
    'graphs': {
        'createMissing': 'true',
        'updateExisting': 'true'
    },
    'groups': {
        'createMissing': 'true'
    },
Example #38
0
nomehosttrigger = []
severidade = []

dicionario = {
    '1': 'Information',
    '2': 'Warning',
    '3': 'Average',
    '4': 'High',
    '5': 'Disaster'
}

url = str(raw_input("Digite a Url: "))
user = str(raw_input("Digite o User: "******"Digite a Senha: "))

zapi = ZabbixAPI(url=url, user=user, password=password)
print(zapi.api_version())

for l in zapi.host.get(output='extend'):
    hostname.append(l['host'])

triggers.append('Trigger')
nomehosttrigger.append('Hostname')
severidade.append('Severidade')

for x in hostname:
    for item in zapi.trigger.get(output='extend', filter={'host': x}):
        nomehosttrigger.append(x)
        triggers.append(item['description'])
        severidade.append(dicionario[item['priority']])
Example #39
0
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

hgname = []
hgid = []
hi = []
hh = []

group = []
host = []

user = str(raw_input("Digite o User: "******"Digite a senha: "))

zapi = ZabbixAPI('http://localhost/zabbix')
zapi.login(user, password)

print(zapi.api_version())

for x in zapi.host.get(output='extend'):
    hi.append(x['hostid'])
    hh.append(x['host'])

for linha in zapi.hostgroup.get(output='extend'):
    hgid.append(linha['groupid'])
    #print linha['name']

for i in hh:
    #print i
    for y in zapi.host.get(selectGroups='extend', filter={'host': i}):
Example #40
0
# -*- coding: utf-8 -*-
from pyzabbix import ZabbixAPI
from pprint import pprint
from transliterate import translit,get_available_language_codes
import MySQLdb

#выполнить подключние к zabbix
zabbix_connect= ZabbixAPI('http://172.20.103.201', user='******',password='******')
sql_connect = MySQLdb.connect(host='192.168.0.5',
                              user='******',
                              password='******',
                              charset='utf8',
                              use_unicode=False,
                              db='radio')

#try:
#    with 
cursor=sql_connect.cursor()
print (cursor)
#cursor.execute("SET NAMES UTF8")
#cursor.execute("SET CHARACTER SET 'utf8'")
#cursor.execute("SET character_set_connection=utf8")
sql='SELECT * FROM devices_bases'

sql2='''SELECT DIP.id,CONCAT_WS(" ", CONCAT("AK-", DC.fio), CONCAT("BS", DB.base, " ", DB.address), CONCAT("RRL-Master ", DRL1.comments), CONCAT("RRL-Slave ", DRL2.comments))
FROM devices_ip_addresses DIP
LEFT JOIN devices_bases DB ON DIP.id = DB.ip_id
LEFT JOIN devices_complekts DC ON DIP.id = DC.ip_id
LEFT JOIN devices_rrl DRL1 ON DIP.id = DRL1.ip_id_master
LEFT JOIN devices_rrl DRL2 ON DIP.id = DRL2.ip_id_slave
WHERE ip = "192.168.32.43"'''
class Zabbix:
    # use only as Static (u can use it as instance but it probably has error and unhandled exception)
    # only static methods and variables

    url = 'http://zabbix.sys.local'  # url of zabbix api
    urlnet = 'http://zabbixnet.sys.local'  # url of zabbix api
    zapi = ZabbixAPI(url)  # pyzabbix class
    zapinet = ZabbixAPI(urlnet)  # pyzabbix class
    login = '******'  # login to access zabbix api
    loginnet = 'xxxxxx'  # login to access zabbixnet api
    password = '******'  # password to access zabbix api
    passwordnet = 'xxxxxxxxx'  # password to access zabbixnet api

    ############################## NO NEEDED ################################################
    def __init__(self):
        self.login = '******'
        self.password = '******'
        self.url = 'http://zabbix.sys.local'
        self.zapi = ZabbixAPI(self.url)
        self.zapi.login(self.login, self.password)

    ############################## NO NEEDED ################################################

    #def __login_before(method):
    #    # @functype - Decorator
    #    # @rtype - None(if excpetion) or function result
    #    # This decorator try log in zabbix api before send request
    #    if not Zabbix.zapi.auth:                                # field auth is string ''
    #        Zabbix.zapi.login(Zabbix.login, Zabbix.password)    # login by ZabbixAPI lib if not loged in
    #    def wrapper(*args, **kwargs):
    #        try:
    #            return method(*args, **kwargs)                  # original method return
    #        except ZabbixAPIException:
    #            try:
    #                Zabbix.zapi.login(Zabbix.login, Zabbix.password)    # try login again
    #                return method(*args, **kwargs)
    #            except:
    #                return None
    #    return wrapper

    ############################## NO NEEDED ################################################
    @classmethod
    def log_in(cls, zabbix='all', anyway=False):
        if zabbix == 'all':
            if anyway:
                cls.zapi.login(cls.login, cls.password)
                cls.zapinet.login(cls.loginnet, cls.passwordnet)
            if not cls.zapi.auth:
                cls.zapi.login(cls.login, cls.password)
            if not cls.zapinet.auth:
                cls.zapinet.login(cls.loginnet, cls.passwordnet)
        elif zabbix == cls.url:
            if anyway:
                cls.zapi.login(cls.login, cls.password)
            if not cls.zapi.auth:
                cls.zapi.login(cls.login, cls.password)
        elif zabbix == cls.urlnet:
            if anyway:
                cls.zapinet.login(cls.loginnet, cls.passwordnet)
            if not cls.zapinet.auth:
                cls.zapinet.login(cls.loginnet, cls.passwordnet)

    @classmethod
    def _get_zapi_by_url(cls, zabbix):
        if zabbix == cls.url:
            return cls.zapi
        elif zabbix == cls.urlnet:
            return cls.zapinet

    @classmethod
    def _request_hosts(cls, zabbix):
        cls.log_in(zabbix)
        zapi = cls._get_zapi_by_url(zabbix)
        try:
            result = zapi.host.get(output="extend", selectGroups="extend")
            return result
        except:
            try:
                cls.log_in(zabbix, anyway=True)
                result = zapi.host.get(output="extend", selectGroups="extend")
                return result
            except:
                return None

    @classmethod
    def request_hg_with_h(cls, zabbix):
        def has_group(groupid, group_list):
            for group in group_list:
                if group.get('id') == groupid:
                    return True
            return False

        current_zabbix = zabbix[7:]
        try:
            result = list()
            rec_hosts = cls._request_hosts(zabbix)
            for host in rec_hosts:
                hostid = host['hostid']
                hostname = host['name']
                groups = host['groups']
                for group in groups:
                    groupid = group['groupid']
                    groupname = group['name']
                    if has_group(groupid, result):
                        for idx, hg in enumerate(result):
                            if hg.get('id') == groupid:
                                result[idx].get('hosts').append({
                                    'id':
                                    hostid,
                                    'name':
                                    hostname,
                                    'zabbix':
                                    current_zabbix
                                })
                    else:
                        result.append({
                            'id':
                            groupid,
                            'name':
                            groupname,
                            'zabbix':
                            current_zabbix,
                            'hosts': [{
                                'id': hostid,
                                'name': hostname,
                                'zabbix': current_zabbix
                            }]
                        })
            return result
        except:
            return None

    @classmethod
    def get_hg_with_h(cls):
        # @rtype - list of host_groups with attached hosts or None by decorator
        # @return - [ { 'id': '@host_group_id', 'name': '@host_group_name', 'zabbix': @zabbixurl, 'hosts': [{'id': '@host_id', 'name': '@host_name', 'zabbix': @zabbixurl}, ...] }, ...]
        # @return - or None
        result = cls.request_hg_with_h(cls.url)
        if result == None:
            result = cls.request_hg_with_h(cls.urlnet)
        else:
            resultnet = cls.request_hg_with_h(cls.urlnet)
            if resultnet != None:
                result.extend(resultnet)
        return result

    @classmethod
    def _request_create_mm(cls, zabbix, **kwargs):
        # kwargs must include 'desciption', 'name', 'start', 'end', 'hostids'
        # 'start' and 'end' - is timestamp
        timeperiods = [{
            'period':
            kwargs['end'] - kwargs['start'],  # duration mm in seconds
            'start_date': kwargs['start'],  # timestamp of start mm
            'timeperiod_type':
            0  # type of mm (0-once, 2-daily, 3-weekly,4-monthly)
        }]
        zapi = cls._get_zapi_by_url(zabbix)
        cls.log_in(zabbix)  # log in if not logged
        try:
            response = zapi.maintenance.create(
                name=kwargs['name'],
                active_since=kwargs['start'],
                active_till=kwargs['end'],
                description=kwargs['description'],
                hostids=kwargs['hostids'],
                timeperiods=timeperiods)
            if 'maintenanceids' in response:  # if hasn't maintenanceids in response Fail return False
                return True
            else:  # else then response has maintenanceids in response Success return True
                return False
        except:
            cls.log_in(zabbix, anyway=true)  # log in again anyway
            response = zapi.maintenance.create(
                name=kwargs['name'],
                active_since=kwargs['start'],
                active_till=kwargs['end'],
                description=kwargs['description'],
                hostids=kwargs['hostids'],
                timeperiods=timeperiods)
            if 'maintenanceids' in response:  # if hasn't maintenanceids in response Fail return False
                return True
            else:  # else then response has maintenanceids in response Success return True
                return False

    @classmethod
    def create_mm(cls, **kwargs):
        # kwargs must include 'desciption', 'name', 'start', 'end', 'hostids'
        # 'hostids' - is [{'id': @id, 'zabbix': @zabbixurl}, ...]
        # 'start' and 'end' - is timestamp
        hostids = list()
        for host in kwargs.get('hostids'):
            if host['zabbix'] == cls.url[7:]:
                hostids.append(host['id'])
        hostidsnet = list()
        for host in kwargs.get('hostids'):
            if host['zabbix'] == cls.urlnet[7:]:
                hostidsnet.append(host['id'])
        zabbix = cls.url
        zabbixnet = cls.urlnet
        result = {'error': {'code': 0, 'message': 'Режим успешно создан'}}
        if len(hostids):
            if cls._request_create_mm(zabbix,
                                      name=kwargs['name'],
                                      start=kwargs['start'],
                                      end=kwargs['end'],
                                      description=kwargs['description'],
                                      hostids=hostids):
                if len(hostidsnet):
                    if not cls._request_create_mm(
                            zabbixnet,
                            name=kwargs['name'],
                            start=kwargs['start'],
                            end=kwargs['end'],
                            description=kwargs['description'],
                            hostids=hostidsnet):
                        result = {
                            'error': {
                                'code':
                                11,
                                'message':
                                'Режим обслуживания для ' + zabbixnet[7:] +
                                ' не был создан, однако режим обслуживания для '
                                + zabbix[7:] + ' был создан'
                            }
                        }
            else:
                if len(hostidsnet):
                    if not cls._request_create_mm(
                            zabbixnet,
                            name=kwargs['name'],
                            start=kwargs['start'],
                            end=kwargs['end'],
                            description=kwargs['description'],
                            hostids=hostidsnet):
                        result = {
                            'error': {
                                'code':
                                12,
                                'message':
                                'Ошибка обращения к Zabbix API режим обслуживание не был создан'
                            }
                        }
                    else:
                        result = {
                            'error': {
                                'code':
                                13,
                                'message':
                                'Режим обслуживания для ' + zabbix[7:] +
                                ' не был создан, однако режим обслуживания для '
                                + zabbixnet[7:] + ' был создан'
                            }
                        }
                else:
                    result = {
                        'error': {
                            'code':
                            12,
                            'message':
                            'Ошибка обращения к Zabbix API режим обслуживание не был создан'
                        }
                    }
        elif len(hostidsnet):
            if not cls._request_create_mm(zabbixnet,
                                          name=kwargs['name'],
                                          start=kwargs['start'],
                                          end=kwargs['end'],
                                          description=kwargs['description'],
                                          hostids=hostidsnet):
                result = {
                    'error': {
                        'code':
                        12,
                        'message':
                        'Ошибка обращения к Zabbix API режим обслуживание не был создан'
                    }
                }
        return result

    @classmethod
    def logout(cls):
        cls.zapi.user.logout()

    @staticmethod
    def validate_auth(login, password):
        try:
            zapi = ZabbixAPI('http://zabbix.sys.local')
            zapi.login(login, password)
            zapi.user.logout()
            return True
        except:
            return False
Example #42
0
parser.add_argument('--verbose', dest = 'verbose', action = 'store_true')
parser.set_defaults(verbose=True)
parser.add_argument('--loglevel', dest = 'loglevel', default = 'ERROR', help = 'Debug level. DEBUG/INFO/WARNING/ERROR/CRITICAL')
parser.add_argument('--max-age', dest = 'max_age', default = 31, help = 'Max age in days for host to be in there')
parser.add_argument('--no-run', dest = 'run', action = 'store_false', help = 'Dont remove any host, just count')
parser.add_argument('--run', dest = 'run', action = 'store_true', help = 'Remove all hosts that expired')
parser.add_argument('--no-matches', dest = 'matches', action = 'store_false', help = 'Dont remove any host that has no prefix')
parser.add_argument('--matches', dest = 'matches', action = 'store_true', help = 'Remove all hosts that has no prefix')
args = parser.parse_args()

TIMEOUT = 30.0
LOGFILE = "/tmp/%s.log" % path.basename(argv[0])
logger = LogPrint(echo=args.verbose, logfile=LOGFILE, loglevel=args.loglevel.upper())

try:
	zapi = ZabbixAPI(args.url,timeout=TIMEOUT)
	zapi.login(args.user,args.password)
except Exception, e:
	logger.error("Unable to login: %s" % (e))
	exit(1)

call = {
		"output": [ "name", "hostid", ],
		"groupids": [ 72 ],
}
hosts = zapi.host.get(**call)
hosts_exclude = []
hosts_no_match = []
date_curr = datetime.now()

"""
Example #43
0
class Zabbix:
    def __init__(self, server, user, password, verify=True):
        """
        Init zabbix class for further needs
        :param user: string
        :param password: string
        :return: pyzabbix object
        """
        self.server = server
        self.user = user
        self.password = password
        # Enable HTTP auth
        s = requests.Session()
        s.auth = (user, password)

        self.zapi = ZabbixAPI(server, s)
        self.zapi.session.verify = False
        self.zapi.login(user, password)
        self.version = self.get_version()

    @pyzabbix_safe()
    def get_version(self):
        """
        Get Zabbix API version
        :return: str
        """
        version = self.zapi.apiinfo.version()
        return version

    @pyzabbix_safe({})
    def get_trigger(self, triggerid):
        """
        Get trigger information
        @param triggerid: string
        @return: dict of data
        """
        trigger = self.zapi.trigger.get(expandComment='true',
                                        expandDescription='true',
                                        triggerids=triggerid)
        return trigger[0]

    @pyzabbix_safe({})
    def get_event(self, triggerid):
        """
        Get event information based on triggerid
        @param triggerid: string
        @return: dict of data
        """
        zbx_event = self.zapi.event.get(select_acknowledges='extend',
                                        expandDescription='true',
                                        object=0,
                                        value=1,
                                        objectids=triggerid)
        if len(zbx_event) >= 1:
            return zbx_event[-1]
        return zbx_event

    @pyzabbix_safe([])
    def get_itservices(self, root=None):
        """
        Return tree of Zabbix IT Services
        root (hidden)
           - service1 (Cachet componentgroup)
             - child_service1 (Cachet component)
             - child_service2 (Cachet component)
           - service2 (Cachet componentgroup)
             - child_service3 (Cachet component)
        :param root: Name of service that will be root of tree.
                    Actually it will not be present in return tree.
                    It's using just as a start point , string
        :return: Tree of Zabbix IT Services
        :rtype: list
        """
        if root:
            root_service = self.zapi.service.get(selectDependencies='extend',
                                                 filter={'name': root})
            try:
                root_service = root_service[0]
            except IndexError:
                logging.error(
                    'Can not find "{}" service in Zabbix'.format(root))
                sys.exit(1)
            service_ids = []
            for dependency in root_service['dependencies']:
                service_ids.append(dependency['serviceid'])
            services = self.zapi.service.get(selectDependencies='extend',
                                             serviceids=service_ids)
        else:
            services = self.zapi.service.get(selectDependencies='extend',
                                             output='extend')
        if not services:
            logging.error(
                'Can not find any child service for "{}"'.format(root))
            return []
        # Create a tree of services
        known_ids = []
        # At first proceed services with dependencies as groups
        service_tree = [i for i in services if i['dependencies']]
        for idx, service in enumerate(service_tree):
            child_services_ids = []
            for dependency in service['dependencies']:
                child_services_ids.append(dependency['serviceid'])
            child_services = self.zapi.service.get(
                selectDependencies='extend', serviceids=child_services_ids)
            service_tree[idx]['dependencies'] = child_services
            # Save ids to filter them later
            known_ids = known_ids + child_services_ids
            known_ids.append(service['serviceid'])
        # At proceed services without dependencies as singers
        singers_services = [
            i for i in services if i['serviceid'] not in known_ids
        ]
        if singers_services:
            service_tree = service_tree + singers_services
        return service_tree
Example #44
0
 def __init__(self, url, user, password):
     self.zb = ZabbixAPI(url)
     self.zb.login(user, password)
Example #45
0
print "\n---------------------------"
print "host_name: %s" % host_name
print "host_invMode: %s" % host_invMode
print "---------------------------\n"

# 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())

#zapi.host.massupdate(hosts=hlookup,inventory_mode=invm)

#11008

if host_invMode == "auto": host_invMode = int(1)
elif host_invMode == "disabled": host_invMode = int(-1)
elif host_invMode == "manual": host_invMode = int('0')
else:
    msg = "Error: unknown inventory mode: %s" % host_invMode
    sys.exit(msg)

#hlookup.append({unicode('hostid'): unicode(hid)})
Example #46
0
if args.no_verify:
 noverify = args.no_verify

# test for needed params
if not username:
 sys.exit("Error: API User not set")

if not password:
 sys.exit("Error: API Password not set")
 
if not api:
 sys.exit("Error: API URL is not set")

# Setup Zabbix API connection
print api
zapi = ZabbixAPI(api, user=username, password=password)
print "OK"

if noverify is True:
 zapi.session.verify = False

# Login to the Zabbix API
print username
#zapi.login(username, password)

##################################
# Start actual API logic
##################################

# Base API call
call={'sortfield': 'clock', 'sortorder': 'DESC', 'output': 'extend', 'source': 0}
Example #47
0
                bot.sendMessage(
                    group_id, 'Nome: ' + w['name'] + '\nURL: ' + s['url'] +
                    '\nStatus: ' + s['status_codes'])


def main():
    sched.start()


daemon = daemon_server('/var/run/TeleZabbix.pid')

if len(sys.argv) >= 2:

    if sys.argv[1] == 'start':
        api, group_id, username, password, server = get_conf()
        zapi = ZabbixAPI(server)
        zapi.login(username, password)
        bot = telepot.Bot(api)
        daemon.start()

    elif sys.argv[1] == 'stop':
        daemon.stop()

    elif sys.argv[1] == 'restart':
        daemon.stop()
        daemon.start()

    elif sys.argv[1] == 'status':
        daemon.is_running()

else:
import argparse
import sys
from pprint import pprint
from pyzabbix import ZabbixAPI, ZabbixAPIException

SERVER_ZABBIX = 'http://192.168.33.65/zabbix'
LOGIN_ZABBIX = 'kolas'
PASSWORD_ZABBIX = ''

z = ZabbixAPI(SERVER_ZABBIX)
z.login(user=LOGIN_ZABBIX, password=PASSWORD_ZABBIX)


def get_users(z):
    try:
        response = z.do_request(method="user.get",
                                params={
                                    "filter": "alias",
                                    "output": ["userid", "alias"]
                                })
        result = response['result']
    except ZabbixAPIException as e:
        print(e)
    print(result)


def get_user_info(z, user_name):
    try:
        response = z.do_request(method="user.get",
                                params={
                                    "search": {
Example #49
0
from pyzabbix import ZabbixAPI, ZabbixAPIException
import sys

# The hostname at which the Zabbix web interface is available
ZABBIX_SERVER = "https://zabbix.tacc.utexas.edu"

zapi = ZabbixAPI(ZABBIX_SERVER)

# Login to the Zabbix API
username = '******'
password = ''

zapi.login(username, password)

host_name = ''

# Get the hosts with the name 'host_name'
hosts = zapi.host.get(filter={"host": host_name},
                      selectInterfaces=["interfaceid"])
Example #50
0
class ZAAS:
    def __init__(self, zab_host, zab_user, zab_pwd):
        """
        Init class
        :param zab_host: Zabbix URL
        :param zab_user: Zabbix Username
        :param zab_pwd: Zabbix Pwd
        """
        self.zab_host = zab_host
        self.zab_user = zab_user
        self.zab_pwd = zab_pwd

    def login(self):
        self.client = ZabbixAPI(self.zab_host)
        self.client.login(self.zab_user, self.zab_pwd)
        self.botoclient = boto3.client('ec2')

    def addhost(self, name, ip, hostgroupid, templates, port=10050):
        """
        Add new EC2 host to zabbix
        :param name: Name used into hostname field
        :param ip: Public ip of the EC2 instance
        :param port: Zabbix agent port
        :param hostgroupid: Group Host ID to add
        :param templates: Template to link into instances host
        :return: None
        """
        params = {
            "host":
            name,
            "groups":
            hostgroupid,
            "interfaces": [{
                "type": 1,
                "main": 1,
                "useip": 1,
                "ip": ip,
                "dns": "",
                "port": 10050
            }]
        }

        if templates:
            params["templates"] = templates
        log.info("Adding %s" % name)
        self.client.host.create(params)

    def get_ec2details(self, instanceid):
        """
        Get ec2 instance details
        :params instanceid: Instance EC2 ID
        :return: {"name": "<private ip without ec2 part>", "ip": "<public ip>"}
        """
        out = {}
        req = self.botoclient.describe_instances(InstanceIds=[instanceid])
        if req:
            name = req["Reservations"][0]["Instances"][0][
                "PrivateDnsName"].split(".")[0]
            ip = req["Reservations"][0]["Instances"][0]["PublicIpAddress"]
            return {"name": name, "ip": ip}

    def gethostid(self, name):
        """
        Get HostID from Zabbix Server
        :params name: Name to check
        :return: HostID
        """
        for hit in self.client.host.get():
            if hit["host"] == name:
                return hit["hostid"]

    def delhost(self, name):
        """
        Delete the host from Zabbix server
        :params name: Host name to delete
        :return: None
        """
        log.info("Deleting %s" % name)
        hostid = self.gethostid(name)
        params = str(hostid)
        if hostid:
            self.client.host.delete(params)
Example #51
0
#!/usr/bin/python
from getpass import getpass
from pyzabbix import ZabbixAPI
ZABBIX_SERVER = 'http://192.168.1.102/zabbix'
zapi = ZabbixAPI(ZABBIX_SERVER)
zapi.login('apiuser', 'apipass')

#Get a hostlist
hostlist = zapi.host.get(output='extend')

for host in hostlist:
    print "Clean not templated items from", host['name']
    itemlist = zapi.item.get(output='extend',
                             filter={"hostid": host['hostid']})

    #Templateid is "0" for non-templated, something else for templated item
    for i in itemlist:
        if i['templateid'] == "0":
            zapi.item.delete(i['itemid'])
            print i['name'], " - deleted"
        else:
            print i['name'], " - preserved"
Example #52
0
import re
from pprint import pprint

from pyzabbix import ZabbixAPI, ZabbixAPIException
from jira.client import JIRA
from consts import SERVER_ZABBIX, LOGIN_ZABBIX, PASSWORD_ZABBIX, SERVER_JIRA, LOGIN_JIRA, PASSWORD_JIRA

# connect to the zabbix
z = ZabbixAPI(SERVER_ZABBIX)
z.login(user=LOGIN_ZABBIX, password=PASSWORD_ZABBIX)

# connect to the jira
jira_options = {'server': SERVER_JIRA}
jira = JIRA(options=jira_options, basic_auth=(LOGIN_JIRA, PASSWORD_JIRA))

issues = jira.search_issues(
    'project = ZNET AND NOT status = Canceled AND NOT status = Closed',
    maxResults=100)
list_issue = []  # empty list for znet numbers
for issue in issues:
    list_issue.append(issue.key)  # add znet issue

# pprint(list_issue)

# find host in group ZNET (id=37)
hosts = z.host.get(groupids=[37])

list_host_names = []  # empty list with hosts names
for host in hosts:
    list_host_names.append(host['name'])
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):
        hostid = self.zbx_api.host.get(filter={'name': hostname},
                                       output='shorten')[0]['hostid']
        log.debug('hostID %s', hostid)
        if not hostid:
            raise ZbxException("hostname: {} not found".format(hostname))

        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):
        hostid = self.zbx_api.host.get(filter={'name': hostname},
                                       output='shorten')[0]['hostid']
        log.debug('hostID %s', hostid)
        if not hostid:
            raise ZbxException("hostname: {} not found".format(hostname))

        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))

        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=[
                'elementid', '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 mapss 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']
Example #54
0
HOST = 'mail.server'                           #IMAP SERVER
USERNAME = '******'                     #IMAP username
PASSWORD = '******'                                           #IMAP user password

eventid = sys.argv[1]                                                  #EventID argument from zbx

#Disable SSL check
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE

with IMAPClient(HOST, ssl_context=ssl_context) as server:
    server.login(USERNAME, PASSWORD)
    select_info = server.select_folder('INBOX')
    messages = server.search(['SUBJECT', eventid])                  #Search zbx EventID in Subject
    for msgid, data in server.fetch(messages, 'RFC822').items():
        email_message = email.message_from_bytes(data[b'RFC822'])
        subj = email_message.get('Subject')
    server.logout()

os.environ['no_proxy'] = '*'                           #Avoid systemwide proxy if needed
#Set ACK without closing problem
zapi = ZabbixAPI('https://zabbix.server/zabbix')                                
zapi.session.verify = False                                                                                                                                        
zapi.login('Login', 'Password')
ack = zapi.event.acknowledge(
        eventids= eventid,
        message= subj[0:16],
        action=0
        )
 def __init__(self):
     self.login = '******'
     self.password = '******'
     self.url = 'http://zabbix.sys.local'
     self.zapi = ZabbixAPI(self.url)
     self.zapi.login(self.login, self.password)
"""

import os
import json
import string
from pyzabbix import ZabbixAPI

#import credentials from external file
import sys
sys.path.insert(0,'/var/lib/zabbix')
import config

# The hostname at which the Zabbix web interface is available
ZABBIX_SERVER = config.url

zapi = ZabbixAPI(ZABBIX_SERVER)

# Login to the Zabbix API
zapi.login(config.username, config.password)

# define the API call from
# https://www.zabbix.com/documentation/3.4/manual/api/reference/maintenance/create
maintenance = {
	"groupids": ["24"],
	"name": "test_maintenance",
	"maintenance_type": 0,
	"active_since": 1532260800,
	"active_till": 1532347200,
	"description": "I am trying to create a maintenance via API",
	"timeperiods": [{
		"timeperiod_type": "0",
Example #57
0
"""
Zabbix stores the DNS name and the IP for each host that it monitors, and
uses one or the other to connect to the host.  It is good practice to make
sure the IP and DNS name are both correct.  This script checks the DNS and
IP for all hosts in Zabbix, compares the IP against an actual DNS lookup,
and fixes it if required.
"""

import socket
from pyzabbix import ZabbixAPI, ZabbixAPIException
from getpass import getpass

# The hostname at which the Zabbix web interface is available
ZABBIX_SERVER = 'https://console.schools.mtm.apps.det.nsw.edu.au/zabbix'

zapi = ZabbixAPI(ZABBIX_SERVER)

# Login to the Zabbix API
zapi.login(input('Zabbix Username: '******'Zabbix Password: '******'dns'] != h['hosts'][0]['host']:
        print('Warning: %s has dns "%s"' % (h['hosts'][0]['host'], h['dns']))
if args.no_verify:
    noverify = args.no_verify

# test for needed params
if not username:
    sys.exit("Error: API User not set")

if not password:
    sys.exit("Error: API Password not set")

if not api:
    sys.exit("Error: API URL is not set")

# Setup Zabbix API connection
zapi = ZabbixAPI(api)

if noverify is True:
    zapi.session.verify = False

# Login to the Zabbix API
zapi.login(username, password)

##################################
# Start actual API logic
##################################

# set the hostname we are looking for
graphid = args.graphid

# Find graph from API
Example #59
-1
def create_hosts(config):
    """
    Take in a config and return a list of Host objects
    This is used in all areas of clustertop so its been
    seperated into its own function.
    :param config: The ConfigParser object holding the clustertop config
    :type config: ConfigParser
    """
    zapi = ZabbixAPI(config.get('main', 'zabbix_host'))
    zapi.login(config.get('main', 'zabbix_user'),
               config.get('main', 'zabbix_pass'))
    return [Host(hn, zapi)
            for hn in config.get('main', 'hosts').split(',')]
Example #60
-1
def get_metrics(host, num_minutes):
    """
    get monitoring statistics of hypervisors using zabbix;
    :param host:
    :param num_minutes:
    :return:
    """
    mem_rs, cpu_rs, disk_rs, net_rs = {}, {}, {}, {}
    mem_rs['time'], mem_rs['value'] = [], []
    cpu_rs['time'], cpu_rs['value'] = [], []
    disk_rs['time'], disk_rs['value'] = [], []
    net_rs['time'], net_rs['value'] = [], []

    zapi = ZabbixAPI(config.ZABBIX_URL)
    zapi.login(config.ZABBIX_USER, config.ZABBIX_PASSWD)
    time_till = time.mktime(datetime.datetime.now().timetuple())
    time_from = time_till - 60 * num_minutes

    cpu_idle_id = zapi.item.get(filter={'host': host, 'name': 'CPU idle time'})[0]['itemid']
    disk_free_id = zapi.item.get(filter={'host': host, 'name': 'disk_usage'})[0]['itemid']
    mem_avail_id = zapi.item.get(filter={'host': host, 'name': 'mem_avail_usage'})[0]['itemid']
    # net_in_id = zapi.item.get(filter={'host':host, 'name':'net_total_in'})[0]['itemid']

    # get statistics of memory usage
    mem_avail_datas = zapi.history.get(itemids=[mem_avail_id], time_from=time_from, time_till=time_till,
                                       output='extend', history=0)
    for item in mem_avail_datas:
        mem_rs['time'].append(item['clock'])
        mem_rs['value'].append(round(100 - float(item['value']), 2))

    # get statistics of cpu util
    cpu_idle_datas = zapi.history.get(itemids=[cpu_idle_id], time_from=time_from, time_till=time_till, output='extend',
                                      history=0)
    for item in cpu_idle_datas:
        cpu_rs['time'].append(item['clock'])
        cpu_rs['value'].append(round(100 - float(item['value']), 2))

    disk_free_datas = zapi.history.get(itemids=[disk_free_id], time_from=time_from, time_till=time_till,
                                       output='extend', history=0)
    for item in disk_free_datas:
        disk_rs['time'].append(item['clock'])
        disk_rs['value'].append(round(float(item['value']), 2))

    '''
    net_in_datas = zapi.history.get(itemids=[net_in_id], time_from=time_from, time_till=time_till, output='extend', history=0)
    for item in net_in_datas:
        net_rs['time'].append(item['clock'])
        net_rs['value'].append(round(float(item['value']), 2))
    '''

    return {'cpu': cpu_rs, 'mem': mem_rs, 'disk': disk_rs, 'net_in': net_rs}