示例#1
0
def main():

    # set config file name
    conf_file = '/etc/zabbix/externalscripts/pystormon/conf.d/pystormon.conf'

    # read network device parameters from config and save it to dict
    nd_parameters = configread(conf_file, 'NetworkDevice', 'device_file',
                               'login', 'password', 'name_space')

    # read storage device parameters from config and save it to another dict
    sd_parameters = configread(conf_file, 'StorageDevice',
                               'storage_cim_map_file')

    # form dictionary of matching storage concepts and cim properties
    # more details in https://www.ibm.com/support/knowledgecenter/STHGUJ_8.3.1/com.ibm.storwize.v5000.831.doc/svc_conceptsmaptocimconcepts_3skacv.html
    with open(sd_parameters['storage_cim_map_file'],
              "r") as storage_cim_map_file:
        sc_maps = load(storage_cim_map_file)

    # open config file with list of monitored storages
    device_list_file = open(nd_parameters['device_file'])

    # unpack storage list to variables
    for device_line in device_list_file:
        device_type, device_name, device_ip = device_line.split(':')

        # connect to each storage via WBEM, get conn object
        if device_type == 'storwize':
            device = WBEMDevice(device_name, device_ip, nd_parameters['login'],
                                nd_parameters['password'],
                                nd_parameters['slack_hook'])
            # get namespace from config, root/ibm by default
            namespace = nd_parameters.get('name_space', 'root/ibm')
            conn = device.Connect(namespace)

            # print all properties for all instances (objects) for cim classes from dict sc_maps
            for storage_concept in sc_maps:
                sc_cim_class = sc_maps[storage_concept]['cim_class']
                instances = conn.EnumerateInstances(
                    sc_cim_class, namespace=nd_parameters['name_space'])
                print(storage_concept, sc_cim_class)
                for instance in instances:
                    for prop_name, prop_value in instance.items():
                        print('  %s: %r' % (prop_name, prop_value))

    device_list_file.close()
示例#2
0
def main():

    # set project name as current directory name
    project = os.path.abspath(__file__).split('/')[-2]

    # get config file name
    conf_file = (f'/etc/zabbix/externalscripts/{project}/{project}.conf')

    # read parameters of IPMI cards and zabbix from config file and save it to dict
    nd_parameters = configread(conf_file, 'NetworkDevice', 'device_file',
                               'login', 'password', 'printing')

    # get variables
    login = nd_parameters['login']
    password = nd_parameters['password']

    # open file with list of monitored IPMI cards
    device_list_file = open(nd_parameters['device_file'])

    device_type, device_name, device_ip = device_list_file.readline().split(
        ':')
    device_ip = device_ip.rstrip('\n')

    # connect to first IPMI card, get conn object
    if device_type in ('ibmc', 'ilo', 'imm'):
        device = IPMICard(device_name, device_ip, login, password)

    # connect to device, get sensors data and create dict of sensors values
    sensors_data = device.Connect().get_sensor_data()

    # parse sensors values and form data for send to zabbix
    for sensor_data in sensors_data:
        print(
            f'type: {sensor_data.type}, name: {sensor_data.name}, '
            f'health: {sensor_data.health}, states: {sensor_data.states}, '
            f'state_ids: {sensor_data.state_ids}, imprecision: {sensor_data.imprecision}'
        )

    device_list_file.close()
示例#3
0
def main():

    # get config file name
    conf_file = (
        f'/etc/zabbix/externalscripts/{project}/conf.d/{project}.conf')

    # read network device parameters from config and save it to dict
    nd_parameters = configread(conf_file, 'NetworkDevice', 'device_file',
                               'login', 'password', 'name_space', 'printing')

    # read storage device parameters from config and save it to another dict
    sd_parameters = configread(conf_file, 'StorageDevice',
                               'monitored_properties_file')

    # get printing boolean variable from config for debugging enable/disable
    printing = eval(nd_parameters['printing'])

    # get variables
    login = nd_parameters['login']
    password = nd_parameters['password']

    # form dictionary of matching storage concepts and cim properties
    # more details in https://www.ibm.com/support/knowledgecenter/STHGUJ_8.3.1/com.ibm.storwize.v5000.831.doc/svc_conceptsmaptocimconcepts_3skacv.html
    with open(sd_parameters['monitored_properties_file'],
              "r") as monitored_properties_file:
        monitored_properties = load(monitored_properties_file)

    # open config file with list of monitored storages
    device_list_file = open(nd_parameters['device_file'])

    # unpack storage list to variables
    for device_line in device_list_file:
        device_type, device_name, device_ip = device_line.split(':')
        device_ip = device_ip.rstrip('\n')

        # connect to each storage via WBEM, get conn object
        if device_type == 'storwize':
            device = WBEMDevice(device_name, device_ip, login, password)
            # get namespace from config, root/ibm by default
            namespace = nd_parameters.get('name_space', 'root/ibm')
            conn = device.Connect(namespace)

            # initialize packet for sending to zabbix
            packet = []

            # iterate through dictionary of monitored storage concepts
            for storage_concept in monitored_properties:
                # get values of object perfomance statistic for all object of each type where perfomance class is given
                if 'cim_perfomance_class' in monitored_properties[
                        storage_concept]:
                    storage_objects_perf = storage_objects_get_perf(
                        conn, device_name,
                        monitored_properties[storage_concept]['cim_class'],
                        monitored_properties[storage_concept]
                        ['cim_property_name'],
                        monitored_properties[storage_concept]
                        ['cim_perfomance_class'],
                        monitored_properties[storage_concept]
                        ['cim_properties_perfomance'])

                    # get statistic for each storage object, form data for sending to zabbix
                    for so_name in storage_objects_perf:
                        for perf_counter_name, perf_counter_value in zip(
                                monitored_properties[storage_concept]
                            ['cim_properties_perfomance'],
                                storage_objects_perf[so_name]):
                            trapper_key = f'{perf_counter_name}[{storage_concept}.{so_name}]'
                            trapper_value = perf_counter_value

                            # form list of data for sending to zabbix
                            packet.append(
                                ZabbixMetric(device_name, trapper_key,
                                             trapper_value))

                            # print data for visual check
                            if printing:
                                print(device_name)
                                print(trapper_key)
                                print(trapper_value)

            # trying send data to zabbix
            zabbix_send(packet, printing, software)

    device_list_file.close()
示例#4
0
import socket

from configread import configread
from pyzabbix import ZabbixSender
from socket import timeout
from sys import stderr

# set project name as current directory name
project = os.path.abspath(__file__).split('/')[-2]

# get config file name
conf_file = (
    f'/etc/zabbix/externalscripts/{project}/conf.d/{project}.conf')

# read network device parameters from config and save it to dict
nd_parameters = configread(conf_file, 'NetworkDevice',
                           'slack_hook', 'zabbix_server')

# get variables for error notifications
slack_hook = nd_parameters['slack_hook']
zabbix_server = nd_parameters['zabbix_server']

hostname = socket.gethostname()


def slack_post(software, message, icon_emoji=':snake:'):
    """ post alarms to slack channel """

    if slack_hook:
        requests.post(slack_hook, json={'username': hostname,
                                        'icon_emoji': icon_emoji,
                                        'text': f'{project}_error: exception in {software}: {message}'})
示例#5
0
def main():

    # set config file name
    conf_file = '/etc/zabbix/externalscripts/pystormon/conf.d/pystormon.conf'

    # read network device parameters from config and save it to dict
    nd_parameters = configread(conf_file, 'NetworkDevice', 'device_file',
                               'login', 'password', 'name_space',
                               'zabbix_server', 'slack_hook')

    # read storage device parameters from config and save it to another dict
    sd_parameters = configread(conf_file, 'StorageDevice',
                               'storage_cim_map_file', 'printing')

    # get printing boolean variable from config for debugging enable/disable
    printing = eval(sd_parameters['printing'])

    # form dictionary of matching storage concepts and cim properties
    # more details in https://www.ibm.com/support/knowledgecenter/STHGUJ_8.3.1/com.ibm.storwize.v5000.831.doc/svc_conceptsmaptocimconcepts_3skacv.html
    with open(sd_parameters['storage_cim_map_file'], "r") as storage_cim_map_file:
        sc_maps = load(storage_cim_map_file)

    # open config file with list of monitored storages
    device_list_file = open(nd_parameters['device_file'])

    # unpack storage list to variables
    for device_line in device_list_file:
        device_type, device_name, device_ip = device_line.split(':')

        # connect to each storage via WBEM, get conn object
        if device_type == 'storwize':
            device = WBEMDevice(device_name, device_ip,
                                nd_parameters['login'],
                                nd_parameters['password'],
                                nd_parameters['slack_hook'])
            # get namespace from config, root/ibm by default
            namespace = nd_parameters.get('name_space', 'root/ibm')
            conn = device.Connect(namespace)

            # initialize packet for sending to zabbix
            packet = []

           # iterate through dictionary of monitored storage concepts
            for storage_concept in sc_maps:
                # get values of object perfomance statistic for all object of each type where perfomance class is given
                if 'cim_perfomance_class' in sc_maps[storage_concept]:
                    storage_objects_perf = storage_objects_get_perf(conn,
                                                                    sc_maps[storage_concept]['cim_class'],
                                                                    sc_maps[storage_concept]['cim_property_name'],
                                                                    sc_maps[storage_concept]['cim_perfomance_class'],
                                                                    sc_maps[storage_concept]['cim_properties_perfomance'])

                    # get statistic for each storage object, form data for sending to zabbix
                    for so_name in storage_objects_perf:
                        for perf_counter_name, perf_counter_value in zip(sc_maps[storage_concept]['cim_properties_perfomance'],
                                                                         storage_objects_perf[so_name]):
                            trapper_key = (perf_counter_name + '['
                                           + storage_concept + '.' + so_name + ']')
                            trapper_value = perf_counter_value

                            # form list of data for sending to zabbix
                            packet.append(ZabbixMetric(
                                device_name, trapper_key, trapper_value))

                            # print data for visual check
                            if printing:
                                print(device_name)
                                print(trapper_key)
                                print(trapper_value)

            # trying send data to zabbix
            try:
                zabbix_send_status = ZabbixSender(
                    nd_parameters['zabbix_server']).send(packet)
                if printing:
                    print('Status of sending data to zabbix:\n',
                          zabbix_send_status)
            except ConnectionRefusedError as error:
                if nd_parameters['slack_hook']:
                    slack_post(nd_parameters['slack_hook'],
                               'Unexpected exception in \"ZabbixSender()' +
                               '.send(packet)\": ' + str(error),
                               nd_parameters['zabbix_server'])
                exit(1)

    device_list_file.close()
示例#6
0
import os
import sys
import time
import ssl

from configread import configread
from pyVmomi import vim, vmodl
from pyVim.task import WaitForTask
from pyVim import connect
from pyVim.connect import Disconnect, SmartConnect, GetSi

# set config file name
conf_file = '/usr/local/orbit/pyvmsnap/conf.d/pyvmsnap.conf'

vcenter_parameters = configread(conf_file, 'vCenter', 'ip', 'login',
                                'password', 'ignore_ssl', 'vms_list_file',
                                'snapshot_name')

parser = argparse.ArgumentParser(
    description='Create or remove ESXi VMs snapshots')
parser.add_argument('operation',
                    metavar='operation',
                    help='create or remove snapshots')
args = parser.parse_args()
print(args.operation)


def get_obj(content, vimtype, name):
    """
     Get the vsphere object associated with a given text name
    """
示例#7
0
            if disk_drive_cim.properties[disk_drive_property].value:
                disk_params_dict[
                    disk_drive_property] = disk_drive_cim.properties[
                        disk_drive_property].value
        disks_params_dict[disk_name] = disk_params_dict

    return disks_params_dict


# read parameters from config file
conf_file = ('/etc/zabbix/externalscripts/' +
             os.path.abspath(__file__).split('/')[-2] + '/' +
             os.path.abspath(__file__).split('/')[-2] + '.conf')

# read parameters and save it to dict for connecting to storage and sending data to zabbix
nd_parameters = configread(conf_file, 'NetworkDevice', 'device_file', 'login',
                           'password', 'name_space', 'zabbix_server')

# open file with list of monitored storages
device_list_file = open(nd_parameters['device_file'])

# create list of disk drives parameters
disk_params_names = [
    'DeviceID', 'Name', 'OperationalStatus', 'EnabledState', 'TechType', 'Use',
    'ErrorSequenceNumber', 'UID', 'Capacity', 'BlockSize', 'MdiskID',
    'MdiskName', 'MemberID', 'EnclosureID', 'SlotID', 'VendorID', 'ProductID',
    'FRUPartNum', 'FRUIdentity', 'RPM', 'FirmwareLevel'
]

# create dictionary of monitored entities with it WBEMs parameters
disk_types = {'DiskDrive': ['IBMTSSVC_DiskDrive', 'Name', disk_params_names]}
示例#8
0
import os

from configread import configread
from datetime import datetime
from pygit2 import Repository, Signature, init_repository
from pynetdevices import CiscoASA, CiscoNexus, CiscoRouter, CiscoSwitch

git_init = False

# set config file name
conf_file = '/usr/local/orbit/pyconfigvc/conf.d/pyconfigvc.conf'

# Read the configuration file with parameters,
# location of configuration file - as in production system
asa_parameters = configread(conf_file, 'CiscoASA', 'enablepw')

git_parameters = configread(conf_file, 'GIT', 'author_name', 'committer_name',
                            'author_email', 'committer_email')

nd_parameters = configread(conf_file, 'NetworkDevice', 'login', 'password',
                           'slack_hook', 'device_file', 'savedir')

if not os.path.isdir(nd_parameters['savedir']):
    os.makedirs(nd_parameters['savedir'])

# Try to create object repository if repository is already exist
try:
    repo = Repository(nd_parameters['savedir'])
except KeyError:
    repo = init_repository(nd_parameters['savedir'])
def main():

    # set config file name
    conf_file = '/etc/zabbix/externalscripts/pystormon/conf.d/pystormon.conf'

    # read network device parameters from config and save it to dict
    nd_parameters = configread(conf_file, 'NetworkDevice', 'device_file',
                               'login', 'password', 'name_space',
                               'zabbix_server', 'slack_hook')

    # read storage device parameters from config and save it to another dict
    sd_parameters = configread(conf_file, 'StorageDevice',
                               'storage_cim_map_file', 'printing')

    # get printing boolean variable from config for debugging enable/disable
    printing = eval(sd_parameters['printing'])

    # form dictionary of matching storage concepts and cim properties
    # more details in https://www.ibm.com/support/knowledgecenter/STHGUJ_8.3.1/com.ibm.storwize.v5000.831.doc/svc_conceptsmaptocimconcepts_3skacv.html
    with open(sd_parameters['storage_cim_map_file'],
              "r") as storage_cim_map_file:
        sc_maps = load(storage_cim_map_file)

    # open config file with list of monitored storages
    device_list_file = open(nd_parameters['device_file'])

    # unpack storage list to variables
    for device_line in device_list_file:
        device_type, device_name, device_ip = device_line.split(':')

        # connect to each storage via WBEM, get conn object
        if device_type == 'storwize':
            device = WBEMDevice(device_name, device_ip, nd_parameters['login'],
                                nd_parameters['password'],
                                nd_parameters['slack_hook'])
            # get namespace from config, root/ibm by default
            namespace = nd_parameters.get('name_space', 'root/ibm')
            conn = device.Connect(namespace)

            # initialize packet for sending to zabbix
            packet = []

            # iterate through dictionary of monitored storage concepts
            for storage_concept in sc_maps:
                # get list of storage objects
                so_names = storage_objects_discovery(
                    conn, sc_maps[storage_concept]['cim_class'],
                    sc_maps[storage_concept]['cim_property_name'])

                so_names_dict = {}
                so_names_list = []

                # create list of disk types and names in JSON
                for so_name in so_names:
                    so_name_json = {
                        "{#SO_TYPE}": storage_concept,
                        "{#SO_NAME}": so_name
                    }
                    so_names_list.append(so_name_json)

                # form data for send to zabbix
                so_names_dict['data'] = so_names_list

                trapper_key = sc_maps[storage_concept]['zabbix_discovery_key']
                trapper_value = str(so_names_dict).replace("\'", "\"")

                # form packet for sending to zabbix
                packet.append(
                    ZabbixMetric(device_name, trapper_key, trapper_value))

                # print data for visual check
                if printing:
                    print(device_name)
                    print(trapper_key)
                    print(trapper_value)

            # trying send data to zabbix
            try:
                zabbix_send_status = ZabbixSender(
                    nd_parameters['zabbix_server']).send(packet)
                if printing:
                    print('Status of sending data to zabbix:\n',
                          zabbix_send_status)
            except ConnectionRefusedError as error:
                if nd_parameters['slack_hook']:
                    slack_post(
                        nd_parameters['slack_hook'],
                        'Unexpected exception in \"ZabbixSender()' +
                        '.send(packet)\": ' + str(error),
                        nd_parameters['zabbix_server'])
                exit(1)

    device_list_file.close()
示例#10
0
import os
import time

from configread import configread
from json import load

# set project name as current directory name
project = os.path.abspath(__file__).split('/')[-2]

# set config file name
conf_file = '/usr/local/pybackup/conf.d/pybackup.conf'

# read configuration parameters and save it to dictionary
backup_parameters = configread(conf_file, 'Backup', 'backup_custom_dirs_file',
                               'backup_main_dir', 'default_storage_period',
                               'debug')

backup_main_dir = backup_parameters['backup_main_dir']
default_storage_period = int(backup_parameters['default_storage_period'])

# get debug boolean variable from config for debugging enable/disable
debug = eval(backup_parameters['debug'])

# form dictionary of backup directories parameters
with open(backup_parameters['backup_custom_dirs_file'],
          "r") as backup_custom_dirs_file:
    backup_custom_dirs = load(backup_custom_dirs_file)

print('Directories with custom config:')
for directory, parameters in backup_custom_dirs.items():
示例#11
0
def main():

    # set project name as current directory name
    project = os.path.abspath(__file__).split('/')[-2]

    software = sys.argv[0]

    if len(sys.argv) == 1:
        print((
            f'Please add argument(s) to call of program for search Storage CIM classes: \n'
            f'Example of syntax: {software} Array Volume'))
        exit(1)

    search_strings = sys.argv[1:]

    # get config file name
    conf_file = (
        f'/etc/zabbix/externalscripts/{project}/conf.d/{project}.conf')

    # read network device parameters from config and save it to dict
    nd_parameters = configread(conf_file, 'NetworkDevice', 'device_file',
                               'login', 'name_space', 'password')

    sd_parameters = configread(conf_file, 'StorageDevice',
                               'detected_properties_file')

    # get variables
    login = nd_parameters['login']
    password = nd_parameters['password']

    # open config file with list of monitored storages
    device_list_file = open(nd_parameters['device_file'])

    # open properties file for writing
    detected_properties_file = open(sd_parameters['detected_properties_file'],
                                    'w')

    # unpack storage list to variables
    for device_line in device_list_file:
        device_type, device_name, device_ip = device_line.split(':')
        device_ip = device_ip.rstrip('\n')

        # connect to each storage via WBEM, get conn object
        if device_type == 'storwize':
            device = WBEMDevice(device_name, device_ip, login, password)
            # get namespace from config, root/ibm by default
            namespace = nd_parameters.get('name_space', 'root/ibm')

            print(f'Connecting to {device_name} ...')
            conn = device.Connect(namespace)

            # try to get all cim classes from storage via WBEM
            try:
                sc_cim_classes = conn.EnumerateClassNames(
                    namespace=nd_parameters['name_space'],
                    DeepInheritance=True)
            except _exceptions.AuthError as error:
                print((
                    f'{project}_error: exception in {software}: can\'t exec query on {device_name}: {error} '
                    f'Check your username/password and permissions of user.'),
                      file=sys.stderr)
                exit(1)
            except _exceptions.ConnectionError as error:
                print((
                    f'{project}_error: exception in {software}: can\'t exec query on {device_name}: {error}. '
                    f'Check the connection to storage or try later.'),
                      file=sys.stderr)
                exit(1)
            except _exceptions.HTTPError as error:
                print((
                    f'{project}_error: exception in {software}: WBEM server return code 400 (Bad Request) on {device_name}: {error}. '
                    f'Check the your request.'),
                      file=sys.stderr)
                exit(1)
            except:
                print(
                    f'{project}_error: exception in {software}: {sys.exc_info()}',
                    file=sys.stderr)
                exit(1)

            # try to get all instances for each cim class from storage via WBEM
            for sc_cim_class in sc_cim_classes:
                for search_string in search_strings:
                    if sc_cim_class.find(search_string) > 0:
                        try:
                            instances = conn.EnumerateInstances(
                                sc_cim_class,
                                namespace=nd_parameters['name_space'])
                        except _exceptions.AuthError as error:
                            print((
                                f'{project}_error: exception in {software}: can\'t exec query on {device_name}: {error} '
                                f'Check your username/password and permissions of user.'
                            ),
                                  file=sys.stderr)
                            exit(1)
                        except _exceptions.ConnectionError as error:
                            print((
                                f'{project}_error: exception in {software}: can\'t exec query on {device_name}: {error}. '
                                f'Check the connection to storage or try later.'
                            ),
                                  file=sys.stderr)
                            exit(1)
                        except _exceptions.HTTPError as error:
                            print((
                                f'{project}_error: exception in {software}: WBEM server return code 400 (Bad Request) on {device_name}: {error}. '
                                f'Check the your request.'),
                                  file=sys.stderr)
                            exit(1)
                        except:
                            print(
                                f'{project}_error: exception in {software}: {sys.exc_info()}',
                                file=sys.stderr)
                            exit(1)

                        for instance in instances:
                            for prop_name, prop_value in instance.items():
                                output_string = (
                                    f'Device: {device_name}, CIM class: {sc_cim_class}\n'
                                    f'Property: {prop_name}, Value: {prop_value}\n'
                                )
                                print(output_string)
                                detected_properties_file.write(
                                    f'{output_string} \n')

    device_list_file.close()
    detected_properties_file.close()
示例#12
0
def main():

    # set project name as current directory name
    project = os.path.abspath(__file__).split('/')[-2]

    # get config file name
    conf_file = (f'/etc/zabbix/externalscripts/{project}/{project}.conf')

    # read parameters of IPMI cards and zabbix from config file and save it to dict
    nd_parameters = configread(conf_file, 'NetworkDevice', 'device_file',
                               'login', 'password', 'printing')

    # read sensor states from config and save it to another dict
    sensor_parameters = configread(conf_file, 'IPMI Sensors',
                                   'sensor_states_map_file')

    # get flag for debug printing from config
    printing = eval(nd_parameters['printing'])

    # get variables
    login = nd_parameters['login']
    password = nd_parameters['password']
    software = sys.argv[0]

    # form dictionary of matching sensor states with returned values
    with open(sensor_parameters['sensor_states_map_file'],
              "r") as sensor_states_map_file:
        sensor_states = load(sensor_states_map_file)

    # open file with list of monitored IPMI cards
    device_list_file = open(nd_parameters['device_file'])

    # unpack IPMI cards list to variables
    for device_line in device_list_file:
        device_type, device_name, device_ip = device_line.split(':')
        device_ip = device_ip.rstrip('\n')

        # connect to each IPMI card, get conn object
        if device_type in ('ibmc', 'ilo', 'imm'):
            device = IPMICard(device_name, device_ip, login, password)

        packet = []

        # connect to device, get sensors data and create dict of sensors values
        sensors_data = device.Connect().get_sensor_data()

        # parse sensors values and form data for send to zabbix
        for sensor_data in sensors_data:
            sensor_state = 100
            sensor_dict = {}

            # fill the dict of states with default values = 100 (Normal)
            for state_counter in range(1, 4):
                type = sensor_data.type
                name = sensor_data.name.rstrip('\x00')
                trapper_key = f'state{state_counter}[{type}.{name}]'
                sensor_dict[trapper_key] = sensor_state

            state_counter = 1

            # check that sensor return one or more states and save this states to dict
            if len(sensor_data.states):
                for sensor_data_state in sensor_data.states:
                    type = sensor_data.type
                    name = sensor_data.name.rstrip('\x00')
                    trapper_key = f'state{state_counter}[{type}.{name}]'
                    sensor_dict[trapper_key] = sensor_states.get(
                        sensor_data_state, 'Unknown')
                    state_counter += 1

            # add sensor states to packet for sending to zabbix
            for trapper_key, trapper_value in sensor_dict.items():
                packet.append(
                    ZabbixMetric(device_name, trapper_key, trapper_value))

                # print data for visual check
                if printing:
                    print(device_name)
                    print(trapper_key)
                    print(trapper_value)

            # add values if exist to packet for sending to zabbix
            if sensor_data.value:
                type = sensor_data.type
                name = sensor_data.name.rstrip('\x00')
                trapper_key = f'value[{type}.{name}]'
                trapper_value = sensor_data.value
                packet.append(
                    ZabbixMetric(device_name, trapper_key, trapper_value))

                # print data for visual check
                if printing:
                    print(device_name)
                    print(trapper_key)
                    print(trapper_value)

        # trying send data to zabbix
        zabbix_send(packet, printing, software)

    device_list_file.close()
示例#13
0
def main():

    # get script name
    software = sys.argv[0]

    # set project name as current directory name
    project = os.path.abspath(__file__).split('/')[-2]

    # get config file name
    conf_file = (
        f'/etc/zabbix/externalscripts/{project}/conf.d/{project}.conf')

    # read network device parameters from config and save it to dict
    nd_parameters = configread(conf_file, 'NetworkDevice', 'device_file',
                               'login', 'password', 'name_space')

    # read storage device parameters from config and save it to another dict
    sd_parameters = configread(conf_file, 'StorageDevice',
                               'monitored_properties_file')

    # form dictionary of matching storage concepts and cim properties
    # more details in https://www.ibm.com/support/knowledgecenter/STHGUJ_8.3.1/com.ibm.storwize.v5000.831.doc/svc_conceptsmaptocimconcepts_3skacv.html
    with open(sd_parameters['monitored_properties_file'],
              "r") as monitored_properties_file:
        monitored_properties = load(monitored_properties_file)

    # get variables
    login = nd_parameters['login']
    password = nd_parameters['password']

    # open config file with list of monitored storages
    device_list_file = open(nd_parameters['device_file'])

    # unpack storage list to variables
    for device_line in device_list_file:
        device_type, device_name, device_ip = device_line.split(':')
        device_ip = device_ip.rstrip('\n')

        # connect to each storage via WBEM, get conn object
        if device_type == 'storwize':
            device = WBEMDevice(device_name, device_ip, login, password)
            # get namespace from config, root/ibm by default
            namespace = nd_parameters.get('name_space', 'root/ibm')
            conn = device.Connect(namespace)

            # print all properties for all instances (objects) for cim classes from dict sc_maps
            for storage_concept in monitored_properties:
                storage_cim_class = monitored_properties[storage_concept][
                    'cim_class']

                # try to request storage via WBEM
                try:
                    instances = conn.EnumerateInstances(
                        storage_cim_class,
                        namespace=nd_parameters['name_space'])
                except _exceptions.AuthError as error:
                    print((
                        f'{project}_error: exception in {software}: can\'t exec query on {device_name}: {error} '
                        f'Check your username/password and permissions of user.'
                    ),
                          file=sys.stderr)
                    exit(1)
                except _exceptions.ConnectionError as error:
                    print((
                        f'{project}_error: exception in {software}: can\'t exec query on {device_name}: {error}. '
                        f'Check the connection to storage or try later.'),
                          file=sys.stderr)
                    exit(1)
                except _exceptions.HTTPError as error:
                    print((
                        f'{project}_error: exception in {software}: WBEM server return code 400 (Bad Request) on {device_name}: {error}. '
                        f'Check the your request.'),
                          file=sys.stderr)
                    exit(1)
                except:
                    print(
                        f'{project}_error: exception in {software}: {sys.exc_info()}',
                        file=sys.stderr)
                    exit(1)

                for instance in instances:
                    for prop_name, prop_value in instance.items():
                        print((
                            f'Device: {device_name}, Concept: {storage_concept}, '
                            f'CIM class: {storage_cim_class}\nProperty: {prop_name}, '
                            f'Value: {prop_value}\n'))

    device_list_file.close()
示例#14
0
def main():

    # set project name as current directory name
    project = os.path.abspath(__file__).split('/')[-2]

    # get config file name
    conf_file = (f'/etc/zabbix/externalscripts/{project}/{project}.conf')

    # read parameters of IPMI cards and zabbix from config file and save it to dict
    nd_parameters = configread(conf_file, 'NetworkDevice', 'device_file',
                               'login', 'password', 'printing')

    # get flag for debug printing from config
    printing = eval(nd_parameters['printing'])

    special_discoveries = [
        'Cable/Interconnect', 'Cooling Device', 'Current', 'Drive Bay', 'Fan',
        'Power Supply', 'Temperature', 'Voltage'
    ]

    # get variables
    login = nd_parameters['login']
    password = nd_parameters['password']
    software = sys.argv[0]

    # open file with list of monitored IPMI cards
    device_list_file = open(nd_parameters['device_file'])

    # unpack IPMI cards list to variables
    for device_line in device_list_file:
        device_type, device_name, device_ip = device_line.split(':')
        device_ip = device_ip.rstrip('\n')

        # connect to each IPMI card, get conn object
        if device_type in ('ibmc', 'ilo', 'imm'):
            device = IPMICard(device_name, device_ip, login, password)

        sensors = {}
        common_sensors_list = []

        # create dictionary of types of sensors
        special_sensors_dict = defaultdict(list)

        # get sensors and create list of common sensors and dictionary of special sensors
        sensors_descriptions = device.Connect().get_sensor_descriptions()
        for sensor_description in sensors_descriptions:
            sensor_type = sensor_description['type'].strip()
            sensor_name = sensor_description['name'].rstrip()
            sensor_json = {"{#TYPE}": sensor_type, "{#NAME}": sensor_name}
            if sensor_type in special_discoveries:
                special_sensors_dict[sensor_type].append(sensor_json)
            else:
                common_sensors_list.append(sensor_json)

        # form common sensors discovery for sending to zabbix
        sensors['data'] = common_sensors_list
        trapper_key = 'ipmi.sensors.discovery'
        trapper_value = str(sensors).replace("\'", "\"")

        # print common sensors discovery for visual check
        if printing:
            print(device_name)
            print(trapper_key)
            for sensor in common_sensors_list:
                print(sensor)

        # form list of data with common sensors discovery for sending to zabbix
        packet = [ZabbixMetric(device_name, trapper_key, trapper_value)]

        # form data with separate special discoveries for sending to zabbix
        for sensor_type in special_sensors_dict:
            sensors['data'] = special_sensors_dict[sensor_type]
            type = sensor_type.replace(" ", "").replace("/", "")
            trapper_key = f'ipmi.sensors.{type}.discovery'
            trapper_value = str(sensors).replace("\'", "\"")

            # add special discoveries to list of data for sending to zabbix
            packet.append(ZabbixMetric(device_name, trapper_key,
                                       trapper_value))

            # print data for visual check
            if printing:
                print(device_name)
                print(trapper_key)
                for sensor in sensors['data']:
                    print(sensor)

        # trying send data to zabbix
        zabbix_send(packet, printing, software)

    device_list_file.close()