Exemplo n.º 1
0
    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)
Exemplo n.º 2
0
 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")
Exemplo n.º 3
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')
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)

Exemplo n.º 5
0
 def test_packet_add_error(self):
     packet = ZabbixPacket()
     with self.assertRaises(TypeError):
         packet.add('host1', 'key1', 22.2, {'a': '1'})
Exemplo n.º 6
0
 def test_clean(self):
     packet = ZabbixPacket()
     packet.add('host1', 'key1', 22.2)
     packet.clean()
     packet2 = ZabbixPacket()
     self.assertEqual(packet.__str__(), packet2.__str__())
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 + ']',
        'Current MBs/sec': 'dell.md.currmbs[' + device + ']',
        'Primary Write Cache Hit %': 'dell.md.writecashhit[' + device + ']',
        'Read %': 'dell.md.readprc[' + device + ']',
        'Primary Read Cache Hit %': 'dell.md.readcashhit[' + device + ']',
        'Total IOs': 'dell.md.totalio[' + device + ']'
    }
Exemplo n.º 8
0
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)
Exemplo n.º 9
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",