示例#1
0
    def setup(self):
        self.logger = self._sensor_service.get_logger(__name__)
        self.trigger_name = 'event.state_change'
        self.trigger_pack = 'icinga2'
        self.trigger_ref = '.'.join([self.trigger_pack, self.trigger_name])
        self.types = ['StateChange']
        self.queue = 'state_change'

        self.api_url = self._config.get('api_url', None)
        self.api_user = self._config.get('api_user', None)
        self.api_password = self._config.get('api_password', None)
        self.certificate = self._config.get('certificate', None)

        if (self.api_user is not None and self.api_user):
            if self.api_password is not None:
                self.client = Client(self.api_url, self.api_user, self.api_password)
                self.logger.info('Icinga2StateChangeSensor initialized with URL: %s User: %s',
                                 self.api_url, self.api_user)
            else:
                raise ValueError("Username defined with no password.")
        elif (self.certificate is not None and self.certificate):
            self.key = self._config.get('key', '')
            self.ca_certificate = self._config.get('ca_certificate', '')
            self.client = Client(self.api_url, certificate=self.certificate, key=self.key,
                                 ca_certificate=self.ca_certificate)
            self.logger.info('Icinga2StateChangeSensor initialized with URL: %s Certificate: %s',
                             self.api_url, self.certificate)
        else:
            raise ValueError("Failed finding authentication method\n \
                     Please specify either username and password or certificate location")
示例#2
0
    def __init__(self, config=None):
        if not config:
            config_environ = os.environ.get('ICINGADIFF_CONFIG')

            if config_environ:
                cfg_file = config_environ
            else:
                cfg_file = os.path.expanduser(DEFAULT_CONFIG_FILE)

            if not os.path.isfile(cfg_file):
                sys.exit(
                    "Please configure icingadiff first (see README.md)".format(
                        cfg_file))
            config = configparser.RawConfigParser()
            config.read(cfg_file)
        url = config['icinga2_web']['url']
        username = config['icinga2_web']['username']
        password = config['icinga2_web']['password']
        self.retries = int(config['icinga2_web'].get('retries', 5))

        if type(config) == configparser.RawConfigParser:
            timeout = config['icinga2_web'].getint('timeout', 30)
            ignore_insecure_requests = config.getboolean(
                'icinga2_web', 'ignore_insecure_requests')
        else:
            timeout = config['icinga2_web'].get('timeout', 30)
            ignore_insecure_requests = config['icinga2_web']\
                .get('ignore_insecure_requests', True)

        self.config = config
        self.client = Client(url,
                             username=username,
                             password=password,
                             ignore_insecure_requests=ignore_insecure_requests,
                             timeout=timeout)
示例#3
0
def _ack_host(host, comment):
    client = Client(config_file='/opt/icinga2api/local.conf')

    client.actions.acknowledge_problem(
        'Host',
        r'match("{0}", host.name)'.format(host),
        'icingaadmin',
        comment)
    def get_client(self, api_url=None, api_user=None, api_password=None):
        if api_url is None:
            api_url = self.config["api_url"]
        if api_user is None:
            api_user = self.config["api_user"]
        if api_password is None:
            api_password = self.config["api_password"]

        return Client(api_url, api_user, api_password)
示例#5
0
def _ack_service(host, service, comment):
    client = Client(config_file='/opt/icinga2api/local.conf')

    client.actions.acknowledge_problem(
        'Service',
        r'match("%s", host.name) && service.name=="%s"' % (host, service),
        'icingaadmin',
        comment,
        sticky=True)
示例#6
0
    def setup(self):
        self.logger = self._sensor_service.get_logger(__name__)
        self.trigger_name = "event.state_change"
        self.trigger_pack = "icinga2"
        self.trigger_ref = ".".join([self.trigger_pack, self.trigger_name])
        self.types = ["StateChange"]
        self.queue = "state_change"

        self.api_url = self._config.get("api_url", None)
        self.api_user = self._config.get("api_user", None)
        self.api_password = self._config.get("api_password", None)
        self.certificate = self._config.get("certificate", None)

        if self.api_user is not None and self.api_user:
            if self.api_password is not None:
                self.client = Client(self.api_url, self.api_user,
                                     self.api_password)
                self.logger.info(
                    "Icinga2StateChangeSensor initialized with URL: %s User: %s",
                    self.api_url,
                    self.api_user,
                )
            else:
                raise ValueError("Username defined with no password.")
        elif self.certificate is not None and self.certificate:
            self.key = self._config.get("key", "")
            self.ca_certificate = self._config.get("ca_certificate", "")
            self.client = Client(
                self.api_url,
                certificate=self.certificate,
                key=self.key,
                ca_certificate=self.ca_certificate,
            )
            self.logger.info(
                "Icinga2StateChangeSensor initialized with URL: %s Certificate: %s",
                self.api_url,
                self.certificate,
            )
        else:
            raise ValueError("Failed finding authentication method\n \
                     Please specify either username and password or certificate location"
                             )
示例#7
0
    def _get_client(self):
        api_url = self.myconfig['api_url']
        api_user = self.myconfig.get('api_user', None)
        api_password = self.myconfig.get('api_password', None)
        certificate = self.myconfig.get('certificate', None)

        if (api_user is not None and api_user):
            if api_password is not None:
                return Client(api_url, api_user, api_password)
            else:
                raise ValueError("Username defined with no password.")
        elif (certificate is not None and certificate):
            key = self.myconfig.get('key', '')
            ca_certificate = self.myconfig.get('ca_certificate', '')
            return Client(api_url,
                          certificate=certificate,
                          key=key,
                          ca_certificate=ca_certificate)
        else:
            raise ValueError("Failed finding authentication method\n \
                     Please specify either username and password or certificate location"
                             )
示例#8
0
    def _get_client(self):
        api_url = self.myconfig["api_url"]
        api_user = self.myconfig.get("api_user", None)
        api_password = self.myconfig.get("api_password", None)
        certificate = self.myconfig.get("certificate", None)

        if api_user is not None and api_user:
            if api_password is not None:
                return Client(api_url, api_user, api_password)
            else:
                raise ValueError("Username defined with no password.")
        elif certificate is not None and certificate:
            key = self.myconfig.get("key", "")
            ca_certificate = self.myconfig.get("ca_certificate", "")
            return Client(api_url,
                          certificate=certificate,
                          key=key,
                          ca_certificate=ca_certificate)
        else:
            raise ValueError("Failed finding authentication method\n \
                     Please specify either username and password or certificate location"
                             )
示例#9
0
 def _ilogin(self):
     """
     Initialize HTTP connection to icinga api
     """
     try:
         self.iapi = Client(
             url=self.url,
             username=self.username,
             password=self.password,
         )
     except Exception as e:
         log.exception(e)
         result, error = self.Error(sys.exc_info())
         return Result(result=result, error=error)
parser.add_argument("-H",
                    "--hosturi",
                    help="URL to icinga2 API",
                    required=True)
parser.add_argument("-u",
                    "--username",
                    help="Username to connect to API",
                    required=True)
parser.add_argument("-p",
                    "--password",
                    help="Password to connect to API",
                    required=True)
parser.add_argument("-g", "--group", help="Group to filter", required=False)
args = parser.parse_args()

client = Client(args.hosturi, args.username, args.password)

hosts = getObjects(client, 'Host')
services = getObjects(client, 'Service')
notifications = getObjects(client, 'Notification')

# debug
#print hosts
#print services
#print notifications

if not args.group:
    h_names = getNameList(hosts, False)
    s_names = getNameList(services, False)
else:
    h_names = getNameList(hosts, args.group)
示例#11
0
import requests
from .models import Icinga
from icinga2api.client import Client

from requests.packages.urllib3.exceptions import InsecureRequestWarning  # Certificate Record Suppression
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)       #


"""When creating a database, override variables and create access settings Icinga"""
#URL=NAME=PASSWORD='******'
icinga_data = list(Icinga.objects.filter(username='******').values())[0]
URL = icinga_data['protocol'] + '://' + icinga_data['ip'] + ':' + icinga_data['port']
NAME = icinga_data['username']
PASSWORD = icinga_data['password']

client = Client(URL, username=NAME, password=PASSWORD)

def request_api(index):
    """API request Icinga"""

    data_api = None
    error_api = True
    try:
        if index == 'group':
            data_api = client.objects.list('HostGroup', attrs=['name'])
        elif index == 'host':
            data_api = client.objects.list('Host', attrs=['name', 'display_name', 'groups'])
        elif index == 'service':
            data_api = client.objects.list('Service', attrs=['display_name'])
        elif index == 'common':
            data_api = client.objects.list('Service', attrs=['host_name',
示例#12
0
    #Information Icinga
    addrIcinga = config.get("addrIcinga")
    idIcinga = config.get("idIcinga")
    passwordIcinga = config.get("passwordIcinga")

    #Information BDD
    hostBDD = config.get("hostBDD")
    userBDD = config.get("userBDD")
    passwordBDD = config.get("passwordBDD")
    database = config.get("database")

    db = mysql.connector.connect(
        host=hostBDD, user=userBDD, password=passwordBDD,
        database=database)  #connexion a la base de donnée
    client = Client(addrIcinga, idIcinga,
                    passwordIcinga)  #connexion a l'API REST

    req = db.cursor()
    req.execute(
        "SELECT SwitchId,NomSwitch,Tag,AdIpCidr FROM Switches INNER JOIN ConfigSwitches ON Switches.ConfigSwitchId = ConfigSwitches.ConfigSwitchId INNER JOIN Modeles ON Switches.ModeleId = Modeles.ModeleId"
    )  # Requete envoyer a la BDD

    reponce = req.fetchall(
    )  #Recuperation de tous les information qu'il a pus trouver a la suite de la requete

    for row in reponce:

        idSwitch = row[0]  #Recuperation de l'id du switch
        switchName = row[1]  #Recuperation du nom du switch
        tag = row[
            2]  #Recuperation de l'information tag ( qui nous dit si le switch a deja été pris en compte null = nouveau , 0 = rien a faire, 1 = doit etre modifier)
示例#13
0
#!/usr/bin/python3

from icinga2api.client import Client
import os
import urllib3

urllib3.disable_warnings()

# source variables from secret.py
exec(
    compile(source=open('/home/m/.i3/secret').read(),
            filename='/home/m/.i3/secret',
            mode='exec'))

client = Client(url, apiuser, apipass)

data = client.status.list('CIB')

sum_services_critical = data['results'][0]['status']['num_services_critical']
sum_services_warning = data['results'][0]['status']['num_services_warning']
sum_services_ok = data['results'][0]['status']['num_services_ok']
print("ЁЯТЪ  " + str(int(sum_services_ok)) + "  тЪая╕П  " +
      str(int(sum_services_warning)) + " тА╝я╕П  " +
      str(int(sum_services_critical)))
示例#14
0
#!/usr/bin/env python3

import sys
import json

# Uncomment this if you wish to import the api library as ugly as me
#sys.path.append('/path/to/python-icinga2api/')

from icinga2api.client import Client

# Your URL here again
client = Client('https://localhost:5665', config_file="./icinga2-api.conf")

states = {0: "OK", 1: "WARNING", 2: "CRITICAL", 3: "UNKOWN"}

state_events = client.events.subscribe(["StateChange"], "state")

for i in state_events:
    json_stuff = json.loads(i)
    state_before = int(json_stuff["check_result"]["vars_before"]["state"])
    state_after = int(json_stuff["check_result"]["vars_after"]["state"])
    host = json_stuff["host"]
    if json_stuff["service"]:
        # Service problem
        service = json_stuff["service"]
        if (state_before == 1) and (state_after > state_before):
            client.actions.send_custom_notification(
                "Service",
                filters=f'service.name=="{service}" && host.name=="{host}"',
                author="script",
                comment="dirty hack")
示例#15
0
start = time.time()

configFile = 'netbox2icinga.yml'
logger.info("OPEN CONFIG FILE %s" % (configFile))
try:
    with open(configFile, 'r') as data:
        config = yaml.load(data)
        data.close()
except:
    logger.error("MISSING OR UNREADABLE CONFIG %s" % (configFile))

# connect to Icinga
icingaUrl = config.get('icinga').get('url')
icingaUser = config.get('icinga').get('user')
icingaPass = config.get('icinga').get('password')
icinga = Client(icingaUrl, icingaUser, icingaPass)

# get all icinga hosts - used to avoid creation of existing objecs
logger.info("READING ICINGA OBJECT LIST")
icingaHosts = icinga.objects.list('Host')

# connect to netbox
token = config.get('netbox').get('token')
server = config.get('netbox').get('server')
logger.info("CONNECTING TO NETBOX SERVER %s" % (server))
nb = nbConnect(server, token)
''' 
read all netbox devices
if device has primary_ip add to icinga
'''