Exemple #1
0
 def __init__(self):
     try:
         self.server = ZabbixSender(Property.ZABBIX_IP,
                                    Property.ZABBIX_PORT)
         print(self.server)
     except Exception as err:
         print(err)
         LogTest.write("Zabbix", "Conectar", "", "zabbix", "ERROR")
Exemple #2
0
 def test_Full(self):
     self.server = ZabbixSender(IP, 10051)
     cur_date_unix = int(datetime.now().timestamp())
     packet = ZabbixPacket()
     packet.add('host2', 'key3', 'IDDQD')
     packet.add('host1', 'key1', 33.1, cur_date_unix)
     self.server.send(packet)
     print(self.server.status)
     self.assertEqual(self.server.status['response'], 'success')
Exemple #3
0
class FullTest(unittest.TestCase):
    def test_Full(self):
        self.server = ZabbixSender(IP, 10051)
        cur_date_unix = int(datetime.now().timestamp())
        packet = ZabbixPacket()
        packet.add('host2', 'key3', 'IDDQD')
        packet.add('host1', 'key1', 33.1, cur_date_unix)
        self.server.send(packet)
        print(self.server.status)
        self.assertEqual(self.server.status['response'], 'success')
Exemple #4
0
class Zabbix:
    def __init__(self):
        try:
            self.server = ZabbixSender(Property.ZABBIX_IP,
                                       Property.ZABBIX_PORT)
            print(self.server)
        except Exception as err:
            print(err)
            LogTest.write("Zabbix", "Conectar", "", "zabbix", "ERROR")

    def send(self, sensor, code):
        try:
            packet = ZabbixPacket()
            ts = time.time()
            packet.add(Property.ZABBIX_HOST, sensor, code, ts)
            print(
                datetime.datetime.fromtimestamp(ts).strftime(
                    "%Y-%m-%d %H:%M:%S"))
            print(packet)
            self.server.send(packet)
        except Exception as err:
            print(err)
            LogTest.write("Zabbix", "Enviar Pacote", "", "zabbix", "ERROR")
class ZabbixSenderTests(unittest.TestCase):
    def setUp(self):
        self.server = ZabbixSender(IP, 10051)

    def test_server_init_host(self):
        self.assertEqual(self.server.server, IP)

    def test_server_init_port(self):
        self.assertEqual(self.server.port, 10051)

    def test_server_init_status(self):
        self.assertEqual(self.server.status, '')

    def test_server_print_info(self):
        server_dict = {'server': str(IP), "port": 10051}
        self.assertEqual(json.loads(self.server.__str__()), server_dict)

    def test_conf_file_parse(self):
        dir = os.path.dirname(__file__)
        filename = os.path.join(dir, 'zabbix_agentd.conf')
        server = ZabbixSender(config=filename)
        self.assertEqual(server.server, '192.168.1.2')
Exemple #6
0
 def _connect_to_zabbix_sender(self):
     try:
         self.zbx_sender = ZabbixSender(self.zbx_addr, 10051)
     except Exception as e:
         raise ZabbixParameterException(
             "Error ZabbixSender - Check ZBX_SERVER.") from e
Exemple #7
0
class ZabbixHelpper(object):
    def __init__(self,
                 group_name=None,
                 template_name=None,
                 zbx_addr=_ZBX_SERVER,
                 zbx_username=_ZBX_USERNAME,
                 zbx_password=_ZBX_PASSWORD,
                 srv_timeout=None):
        self.group_name = group_name
        self.template_name = template_name
        self.srv_timeout = int(srv_timeout or _ZBX_SERVER_TIMEOUT)
        self.zbx_addr = zbx_addr
        self.zbx_username = zbx_username
        self.zbx_password = zbx_password
        self.zapi = None
        self._connect_to_zabbix()
        self._connect_to_zabbix_sender()

    def _connect_to_zabbix(self, retry=0):
        try:
            self.zapi = ZabbixAPI(server="http://%s" % self.zbx_addr,
                                  timeout=self.srv_timeout)
            self.zapi.login(self.zbx_username, self.zbx_password)
        except Exception as e:
            if retry < _ZBX_CONNECT_MAX_RETRY:
                retry += 1
                print("[_connect_to_zabbix] Error connecting to Zabbix Server."
                      " Retrying in %ssecs!" % _ZBX_CONNECT_WAIT)
                print("[_connect_to_zabbix] %s" % e)
                time.sleep(_ZBX_CONNECT_WAIT)
                self._connect_to_zabbix(retry)
            else:
                raise e

    def _connect_to_zabbix_sender(self):
        try:
            self.zbx_sender = ZabbixSender(self.zbx_addr, 10051)
        except Exception as e:
            raise ZabbixParameterException(
                "Error ZabbixSender - Check ZBX_SERVER.") from e

    def _do_request(self, method, *args, **kwargs):
        while 1:
            try:
                return getattr(self.zapi, method).dummy(*args, **kwargs)
            except Exception as e:
                if ("Error -32602: Invalid params., "
                        "Host with the same name") in str(e):
                    ex_msg = 'Host %s already exists' % \
                        kwargs.get('host', '')
                    raise ZabbixAlreadyExistsException(ex_msg) from e
                else:
                    # so tento reconectar se nao for hostduplicado
                    print("[_do_request] Error connecting to Zabbix Server."
                          " Retrying in %ssecs!" % _ZBX_CONNECT_WAIT)
                    print("[_do_request] %s" % e)
                    time.sleep(_ZBX_CONNECT_WAIT)
                    self._connect_to_zabbix()

    # Get Zabbix group ID by hostgroup name
    def _getHostgroupId(self, hostgroup_name):
        hostgroups = self._do_request('hostgroup.get',
                                      filter={'name': hostgroup_name})
        if not hostgroups:
            raise ZabbixNotFoundException("Hostgroup not found")
        return int(hostgroups[0]['groupid'])

    # Get Zabbix template ID by template name
    def _getTemplateId(self, template_name):
        templates = self._do_request('template.get',
                                     filter={'name': template_name})
        if not templates:
            raise ZabbixNotFoundException("Template not found")
        return int(templates[0]['templateid'])

    def createHost(self, host_name, ip, group_name=None, template_name=None):
        """ Create one host in the Zabbix server

        Raises ZabbixNotFound exceptions from:
            _getTemplateId
            _getHostgroupId

        Raises ZabbixAlreadyExistsException on atempt to create an existent
        host (by hostname)


        Usage example:

        zbxHelpper = ZabbixHelpper()
        try:
            id = zbxHelpper.createHost(
                'my_host',
                '10.10.10.10',
                'my_grp',
                'my_template'
            )
            print(id)
        except ZabbixAlreadyExistsException as e:
            print(e.message)

        or setting default group_name and template_name on class initialization

        zbxHelpper = ZabbixHelpper(
            group_name='my_grp',
            template_name="my_template"
        )
        try:
            id = zbxHelpper.createHost(
                'my_host',
                '10.10.10.10'
            )
            print(id)
        except ZabbixAlreadyExistsException as e:
            print(e.message)


        """
        if not group_name:
            if self.group_name:
                group_name = self.group_name
            else:
                raise ZabbixParameterException(
                    "No group_name given as parameter or"
                    "on class initialization")
        if not template_name:
            if self.template_name:
                template_name = self.template_name
            else:
                raise ZabbixParameterException(
                    "No template_name given as parameter or"
                    "on class initialization")

        template_id = self._getTemplateId(template_name)
        host_group_id = self._getHostgroupId(group_name)

        groups = [{'groupid': host_group_id}]
        templates = [{'templateid': template_id}]
        interfaces = [{
            'ip': ip,
            'useip': 1,
            "dns": "",
            "main": 1,
            "type": 1,
            "port": "10050"
        }]
        inventory = {
            "notes": "my notes",
            "tag": "BGAN",
            "installer_name": "Netvision"
        }

        call_rtrn = self._do_request('host.create',
                                     groups=groups,
                                     host=host_name,
                                     inventory_mode="1",
                                     inventory=inventory,
                                     templates=templates,
                                     interfaces=interfaces)
        return call_rtrn

    def send_host_availability(self,
                               host_name,
                               arrived_datetime,
                               positive_availability=1,
                               retry=0):
        """ Create availability of one host in Zabbix

         The third parameter on package.add ()1 is the default value for
         positive availability.
        """
        packet = ZabbixPacket()
        packet.add(host_name, _ZBX_SENDER_KEY, positive_availability,
                   datetime.timestamp(arrived_datetime))
        self.zbx_sender.send(packet)
        processed = 0
        try:
            ret_dct = dict(
                item.split(':')
                for item in self.zbx_sender.status['info'].split(";"))
            processed = int(ret_dct['processed'])
        except Exception as e:
            print("[send_host_availability] Error parsing zbx response")
            print("[send_host_availability] %s" % e)

        if processed == 0 and retry < _ZBX_CONNECT_MAX_RETRY:
            print("[send_host_availability] Packet not processed by zbx"
                  " Retrying in %ssecs!" % _ZBX_CONNECT_WAIT)
            time.sleep(_ZBX_CONNECT_WAIT)
            retry += 1
            self.send_host_availability(host_name, arrived_datetime,
                                        positive_availability, retry)
import os
import sys

storageName = sys.argv[1]
zbxName = sys.argv[2]
mdName = sys.argv[3]

os.system('SMcli -n {} -S -quick -c "save storageArray performanceStats file=\\"/var/log/{}.stat\\";"'.format(storageName, mdName))

file_stat = '/var/log/{}.stat'.format(mdName)
df = pd.read_csv(file_stat, skiprows=3)
lld_data = {'data': []}
for dev in df[ ~df['Objects'].str.contains('Expansion Enclosure')]['Objects'][2:].tolist():
    lld_data['data'].append({'{#MDDEV}': dev})

packet = ZabbixPacket()
packet.add(zbxName, 'dell.md.devices', json.dumps(lld_data))
for ind, dev in df[ ~df['Objects'].str.contains('Expansion Enclosure')][2:].iterrows():
    packet.add(zbxName, 'dell.md.currios[{}]'.format(dev['Objects']), dev['Current IOs/sec'])
    packet.add(zbxName, 'dell.md.curriol[{}]'.format(dev['Objects']), dev['Current IO Latency'])
    packet.add(zbxName, 'dell.md.currmbs[{}]'.format(dev['Objects']), dev['Current MBs/sec'])
    packet.add(zbxName, 'dell.md.writecashhit[{}]'.format(dev['Objects']), dev['Primary Write Cache Hit %'])
    packet.add(zbxName, 'dell.md.readprc[{}]'.format(dev['Objects']), dev['Read %'])
    packet.add(zbxName, 'dell.md.readcashhit[{}]'.format(dev['Objects']), dev['Primary Read Cache Hit %'])
    packet.add(zbxName, 'dell.md.totalio[{}]'.format(dev['Objects']), dev['Total IOs'])


result = ZabbixSender().send(packet)
print(result)

 def test_conf_file_parse(self):
     dir = os.path.dirname(__file__)
     filename = os.path.join(dir, 'zabbix_agentd.conf')
     server = ZabbixSender(config=filename)
     self.assertEqual(server.server, '192.168.1.2')
 def setUp(self):
     self.server = ZabbixSender(IP, 10051)
#!/usr/bin/env python3
import pandas as pd
import json
from ZabbixSender import ZabbixPacket, ZabbixSender
import os
import sys, subprocess

zabbix_server = ZabbixSender("zabbix.example.org", 10051)
storage_host = sys.argv[1]
zabbix_host = sys.argv[2]
file_stat = "/tmp/" + zabbix_host + "-" + storage_host + ".stat"

subprocess.run([
    '/usr/lib/zabbix/externalscripts/SMcli', storage_host, '-S', '-quick',
    '-c', 'save storageArray performanceStats file="' + file_stat + '";'
],
               stdout=subprocess.PIPE,
               stderr=subprocess.STDOUT)

df = pd.read_csv(file_stat, skiprows=3)
lld_data = {'data': []}
packet = ZabbixPacket()

for index, dev in df[~df['Objects'].str.contains('Expansion Enclosure'
                                                 )][2:].iterrows():
    device = dev['Objects']
    lld_data['data'].append({'{#MDDEV}': device})

    map_metrics = {
        'Current IOs/sec': 'dell.md.currios[' + device + ']',
        'Current IO Latency': 'dell.md.curriol[' + device + ']',
def main():
    logger.debug('Loading config...')
    config = configparser.ConfigParser()
    config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                               'tableausync.conf')
    config.read_file(open(config_path))

    config_sections = config.sections()

    do_something = config.get('Common', 'do_something')
    if do_something in [
            'True', 'true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly',
            'uh-huh'
    ]:
        do_something = True
    else:
        do_something = False
        logger.info('It is TEST RUN')

    ad_server = config.get('AD', 'server')
    ad_user = config.get('AD', 'user')
    ad_password = config.get('AD', 'password')
    tableau_root_ou = config.get('AD', 'tableau_root_ou')
    users_root_ou = config.get('AD', 'users_root_ou')
    tableau_server = config.get('Tableau', 'server')
    tableau_admin = config.get('Tableau', 'username')
    tableau_password = config.get('Tableau', 'password')
    tableau_service_accounts = config.get('Tableau',
                                          'serviceAccounts').split(',')

    ad = AD(ad_server, ad_user, ad_password, tableau_root_ou, users_root_ou)

    tableau_auth = TSC.TableauAuth(tableau_admin, tableau_password)
    tableau = TSC.Server(tableau_server)

    try:
        tableau.auth.sign_in(tableau_auth)
    except Exception as e:
        logger.debug("Failed to connect to {0}".format(tableau_server))
        logger.debug(e.message)
        sys.exit()

    ad_ous = ad.get_tableau_ous()
    tableau_sites = [site for site in TSC.Pager(tableau.sites)]
    for current_site in tableau_sites:
        if any(current_site.name in ad_ou.get('name') for ad_ou in ad_ous):
            logger.info("Tableau site: {0}".format(current_site.name))
            tableau_auth = TSC.TableauAuth(tableau_admin, tableau_password,
                                           current_site.content_url)
            tableau.auth.sign_in(tableau_auth)
            tableau_all_site_users = [
                user for user in TSC.Pager(tableau.users)
                if user.site_role != 'Unlicensed'
            ]
            tableau_unlicensed_users = [
                user for user in TSC.Pager(tableau.users)
                if user.site_role == 'Unlicensed'
            ]

            logger.info('Revision users on site')
            ad_all_site_users = ad.get_all_site_users(current_site)
            tableau_all_site_users_set = set(
                [user.name for user in tableau_all_site_users])
            ad_all_site_users_set = set(
                [user.sAMAccountName.value for user in ad_all_site_users])
            old_users_set = tableau_all_site_users_set - ad_all_site_users_set
            new_users_set = ad_all_site_users_set - tableau_all_site_users_set
            old_users_set -= set(tableau_service_accounts)
            old_users = [
                tableau_all_site_user
                for tableau_all_site_user in tableau_all_site_users
                if any(olduser == tableau_all_site_user.name
                       for olduser in old_users_set)
            ]

            logger.debug("Old users: {0}".format(old_users_set))
            if do_something:
                for old_user in old_users:
                    logger.debug("Deleting user: {0}".format(old_user.name))
                    tableau.users.populate_workbooks(old_user)
                    if old_user.workbooks.__len__() > 0:
                        old_user.site_role = 'Unlicensed'
                        tableau.users.update(old_user)
                    else:
                        tableau.users.remove(old_user.id)

            logger.debug("New users: {0}".format(new_users_set))
            if do_something:
                for new_user in new_users_set:
                    if new_user in [
                            user.name for user in tableau_unlicensed_users
                    ]:
                        tableau_user = [
                            user for user in tableau_unlicensed_users
                            if user.name == new_user
                        ].pop()
                        logger.info(
                            'Change site role to Interactor for {0}'.format(
                                new_user))
                        tableau_user.site_role = 'Interactor'
                        tableau.users.update(tableau_user)

                    else:
                        logger.debug("Creating user: {0}".format(new_user))
                        ad_user_data = ad.get_user_by_samaccountname(new_user)
                        password = ''.join(
                            random.choices(string.ascii_letters +
                                           string.digits,
                                           k=32))
                        new_user = TSC.UserItem(
                            name=ad_user_data[0].sAMAccountName.value,
                            site_role='Interactor')
                        new_user = tableau.users.add(new_user)
                        new_user.email = ad_user_data[0].mail.value
                        new_user.fullname = ad_user_data[0].name.value
                        new_user.password = password
                        new_user = tableau.users.update(new_user)

            tableau_all_site_users = [
                user for user in TSC.Pager(tableau.users)
            ]
            for site_user in [
                    user for user in tableau_all_site_users
                    if user.site_role != 'Unlicensed'
            ]:
                if not any(site_user.name in tableau_service_account
                           for tableau_service_account in
                           tableau_service_accounts):
                    tableau_user = tableau.users.get_by_id(site_user.id)
                    ad_user = ad.get_user_by_samaccountname(site_user.name)
                    if tableau_user.fullname != ad_user[
                            0].name.value and do_something:
                        logger.info("Changing userdata {0}".format(
                            tableau_user.name))
                        tableau_user.fullname = ad_user[0].name.value
                        tableau_user.email = ad_user[0].mail.value
                        tableau.users.update(tableau_user)

            logger.info('Revision groups on site')
            ad_site_groups = [
                group.name.value for group in ad.get_site_groups(current_site)
            ]
            tableau_site_groups = [
                group for group in TSC.Pager(tableau.groups)
            ]
            new_groups = set(ad_site_groups) - set([
                tablesu_site_group.name
                for tablesu_site_group in tableau_site_groups
            ])
            old_groups = set([
                tableau_site_group.name
                for tableau_site_group in tableau_site_groups
            ]) - set(ad_site_groups)
            old_groups.remove('All Users')

            logger.debug("New groups{0}".format(new_groups))
            if do_something:
                for new_group in new_groups:
                    newgroup = TSC.GroupItem(new_group)
                    tableau.groups.create(newgroup)

            logger.debug("Old groups{0}".format(old_groups))
            if do_something:
                for old_group in old_groups:
                    group_id = [
                        group.id for group in tableau_site_groups
                        if group.name == old_group
                    ]
                    tableau.groups.delete(group_id.pop())

            logger.info('Revision group members on site')
            all_tableau_groups = [group for group in TSC.Pager(tableau.groups)]
            opts = TSC.RequestOptions(pagesize=1000)
            for group in all_tableau_groups:
                if group.name != 'All Users':
                    tableau.groups.populate_users(group, opts)
                    tableau_members_set = set(
                        [user.name for user in group.users])
                    ad_members = ad.get_members_by_groupname(group.name)
                    ad_members_set = set(
                        [user.sAMAccountName.value for user in ad_members])
                    new_members_set = ad_members_set - tableau_members_set
                    old_members_set = tableau_members_set - ad_members_set

                    logger.debug("New members:{0}".format(new_members_set))
                    logger.debug("Old members{0}".format(old_members_set))

                    if do_something:
                        for new_member in new_members_set:
                            logger.debug("Adding user:{0}".format(new_member))
                            user_id = [
                                user.id for user in tableau_all_site_users
                                if user.name == new_member
                            ].pop()
                            tableau.groups.add_user(user_id=user_id,
                                                    group_item=group)

                    if do_something:
                        for old_member in old_members_set:
                            logger.debug(
                                "Removing user:{0}".format(old_member))
                            user_id = [
                                user.id for user in tableau_all_site_users
                                if user.name == old_member
                            ][0]
                            tableau.groups.remove_user(user_id=user_id,
                                                       group_item=group)

    if 'Zabbix' in config_sections:
        zabbix_config_path = config.get('Zabbix', 'zabbix_agentd_conf')
        zabbix_config = open(zabbix_config_path).read()
        zabbix_server = re.search(r'ServerActive=(.+)', zabbix_config).group(1)
        zabbix_item = config.get('Zabbix', 'item')
        zabbix_hostname = re.search(r'Hostname=(.+)', zabbix_config).group(1)
        server = ZabbixSender(zabbix_server, 10051)
        packet = ZabbixPacket()
        packet.add(zabbix_hostname, zabbix_item, '1')
        server.send(packet)
Exemple #13
0
#!/usr/bin/python3.6
# coding: utf-8
"""
version 1.0 Author: Ledivan B. Marques
            Email:	[email protected]
"""
import requests
import datetime
import time
import argparse
from ZabbixSender import ZabbixSender, ZabbixPacket

server = ZabbixSender(' ', 10051)
packet = ZabbixPacket()

start = time.time()
now = datetime.datetime.today()
date_start = now + datetime.timedelta(days=35)
date_end = now + datetime.timedelta(days=45)

parser = argparse.ArgumentParser()
parser.add_argument('--tipo', help='Nacional ou Interfacional')
args = parser.parse_args()

url = " "

nacional = '''{{
 "Adults": "1",
 "Children": "0",
 "Infants": "0",
 "DirectFlight": "true",