示例#1
0
文件: __init__.py 项目: ppepos/pynag
def find_command_file(cfg_file=None):
    """
    Returns path to nagios command_file by looking at what is defined in nagios.cfg

    Args:
        cfg_file (str): Path to nagios.cfg configuration file

    Returns:
        str. Path to the nagios command file

    Raises:
        CommandError

    """
    global path_to_command_file

    # If we have been called before, the path should be cached in a global variable
    if path_to_command_file:
        return path_to_command_file

    # If we reach here, we have to parse nagios.cfg to find path
    # to our command file
    c = config(cfg_file=cfg_file)
    command_file = c.get_cfg_value('command_file')

    if not command_file:
        raise CommandError("command_file not found in your nagios.cfg (%s)" %
                           c.cfg_file)

    path_to_command_file = command_file
    return command_file
示例#2
0
文件: __init__.py 项目: ppepos/pynag
def find_command_file(cfg_file=None):
    """
    Returns path to nagios command_file by looking at what is defined in nagios.cfg

    Args:
        cfg_file (str): Path to nagios.cfg configuration file

    Returns:
        str. Path to the nagios command file

    Raises:
        CommandError

    """
    global path_to_command_file

    # If we have been called before, the path should be cached in a global variable
    if path_to_command_file:
        return path_to_command_file

    # If we reach here, we have to parse nagios.cfg to find path
    # to our command file
    c = config(cfg_file=cfg_file)
    command_file = c.get_cfg_value('command_file')

    if not command_file:
        raise CommandError("command_file not found in your nagios.cfg (%s)" % c.cfg_file)

    path_to_command_file = command_file
    return command_file
示例#3
0
def get_all_commands():
    if commands:
        return commands
    nc = config(NAGIOS_MAIN_CONF)
    nc.parse()
    all_command = nc.data['all_command']
    for command in all_command:
        commands[command['command_name']] = command['command_line']
示例#4
0
def get_all_commands():
    if commands:
        return commands
    nc = config(NAGIOS_MAIN_CONF)
    nc.parse()
    all_command = nc.data["all_command"]
    for command in all_command:
        commands[command["command_name"]] = command["command_line"]
示例#5
0
def get_nagios_data():
    nc = config(nagios_cfg)
    nc.parse()
    # crash if there's no data on nc.data
    if nc.data == None:
	nc.data = {}
    if not nc.data.has_key('all_host'):
	nc.data['all_host'] = []
    if not nc.data.has_key('all_hostgroup'):
        nc.data['all_hostgroup'] = []
    return nc
示例#6
0
def get_nagios_data():
    nc = config(nagios_cfg)
    nc.parse()
    # crash if there's no data on nc.data
    if nc.data == None:
        nc.data = {}
    if not nc.data.has_key('all_host'):
        nc.data['all_host'] = []
    if not nc.data.has_key('all_hostgroup'):
        nc.data['all_hostgroup'] = []
    return nc
示例#7
0
def find_command_file(cfg_file=None):
    """ Returns path to nagios command_file by looking at what is defined in nagios.cfg """
    c = config(cfg_file=cfg_file)
    c.parse()
    command_file = None
    for k,v in c.maincfg_values:
        if k == 'command_file':
            command_file = v
            break
    if not command_file:
        if not command_file:
            raise PynagError("command_file not found in your nagios.cfg (%s)" % c.cfg_file)
    return command_file
示例#8
0
def find_command_file(cfg_file=None):
    """ Returns path to nagios command_file by looking at what is defined in nagios.cfg """
    c = config(cfg_file=cfg_file)
    c.parse()
    command_file = None
    for k, v in c.maincfg_values:
        if k == 'command_file':
            command_file = v
            break
    if not command_file:
        if not command_file:
            raise PynagError("command_file not found in your nagios.cfg (%s)" %
                             c.cfg_file)
    return command_file
示例#9
0
def post(hosts=None, services=None, check_existance=True, create_services=True, create_hosts=False):
    """ Puts a list of hosts into local instance of nagios checkresults
    Arguments:
      hosts               -- list of dicts, like one obtained from get_checkresults
      services            -- list of dicts, like one obtained from get_checkresults
      check_existance     -- If True, check (and log) if objects already exist before posting
      create_services -- If True, autocreate non-existing services (where the host already exists)
      create_hosts    -- If True, autocreate non-existing hosts
    """

    nagios_config = config()
    nagios_config.parse_maincfg()
    check_result_path = nagios_config.get_cfg_value("check_result_path")


    fd, filename = tempfile.mkstemp(prefix='c', dir=check_result_path)
    if not hosts:
        hosts = []
    if not services:
        services = []

    if check_existance:
        checkresults_overhaul(hosts, services, create_services=create_services, create_hosts=create_hosts)
    checkresults = '### Active Check Result File Made by Nago ###\n'
    checkresults += 'file_time=%s' % (int(time.time()))
    checkresults = ''

    for host in hosts:
        checkresults += _format_checkresult(**host)
    for service in services:
        checkresults += _format_checkresult(**service)
    os.write(fd, checkresults)

    # Cleanup and make sure our file is readable by nagios
    os.close(fd)
    os.chmod(filename, 0644)

    # Create an ok file, so nagios knows it's ok to reap our changes
    file('%s.ok' % filename, 'w')
示例#10
0
    def setUp(self):
        """
        Set to the current defaults of the control.daemon() class
        It's probably dangerous to read these variables from the class object itself
        """
        self.config = config()

        # Ignore futurewarnings for nagios_init
        warnings.simplefilter("ignore", FutureWarning)

        self.nagios_bin = self.config.guess_nagios_binary()
        self.nagios_cfg = '/etc/nagios/nagios.cfg'
        self.service_name = 'nagios'
        self.nagios_init = "service nagios"

        # Save reference to mocked functions
        self.runCommand = pynag.Control.runCommand
        self.osexists = os.path.exists

        self.control = pynag.Control.daemon(nagios_bin=self.nagios_bin,
                                            nagios_cfg=self.nagios_cfg,
                                            nagios_init=self.nagios_init,
                                            service_name=self.service_name)
示例#11
0
    def setUp(self):
        """
        Set to the current defaults of the control.daemon() class
        It's probably dangerous to read these variables from the class object itself
        """
        self.config = config()

        # Ignore futurewarnings for nagios_init
        warnings.simplefilter("ignore", FutureWarning)

        self.nagios_bin=self.config.guess_nagios_binary()
        self.nagios_cfg='/etc/nagios/nagios.cfg'
        self.service_name = 'nagios'
        self.nagios_init = "service nagios"

        # Save reference to mocked functions
        self.runCommand = pynag.Control.runCommand
        self.osexists = os.path.exists

        self.control = pynag.Control.daemon(
                nagios_bin=self.nagios_bin,
                nagios_cfg=self.nagios_cfg,
                nagios_init=self.nagios_init,
                service_name=self.service_name)
示例#12
0
#!/usr/bin/python
import sys

if len(sys.argv) != 2:
    sys.stderr.write("Usage:  %s 'Host Alias'\n" % (sys.argv[0]))
    sys.exit(2)

## This is for the custom nagios module
sys.path.insert(1, '../')
from pynag.Parsers import config

target_host = sys.argv[1]

## Create the plugin option
nc = config('/etc/nagios/nagios.cfg')
nc.extended_parse()

nc.cleanup()

## Find services that this host belongs to
if not nc.get_host(target_host):
    sys.stderr.write("%s does not exist\n" % target_host)
    sys.exit(2)

for service_description in nc.get_host(target_host)['meta']['service_list']:
    service = nc.get_service(target_host, service_description)

    ## Check to see if this is the only host in this service
    host_list = []
    if 'host_name' in service:
        for host in nc._get_list(service, 'host_name'):
示例#13
0
#!/usr/bin/python
import sys

if len(sys.argv) != 2:
    sys.stderr.write("Usage:  %s 'Command Name'\n" % (sys.argv[0]))
    sys.exit(2)

## This is for the custom nagios module
sys.path.insert(1, '../')
from pynag.Parsers import config

target_item = sys.argv[1]

## Create the plugin option
nc = config('/etc/nagios/nagios.cfg')
nc.parse()


item = nc.get_command(target_item)

if not item:
    sys.stderr.write("Item not found: %s\n" % item)
    sys.exit(2)

print nc.print_conf(item)
示例#14
0
def main():

    if debug:
        with indent(4, quote='>>>'):
            puts(colored.white('---------- DEBUG ----------'))
            puts(colored.red('Aruments passed in: ') + str(args.all))
            puts(colored.red('Flags detected: ') + str(args.flags))
            puts(colored.red('Files detected: ') + str(args.files))
            puts(colored.red('NOT Files detected: ') + str(args.not_files))
            puts(colored.red('Grouped Arguments: ') + str(dict(args.grouped)))
            puts(colored.white('---------- DEBUG ----------'))
        print

    mode = None
    what = None
    options = []

    if '--options' in args.flags:
        try:
            for option in dict(args.grouped)['--options'][0].split(','):
                options.append(option)
        except:
            pass

    if '-o' in args.flags:
        try:
            for option in dict(args.grouped)['-o'][0].split(','):
                options.append(option)
        except:
            pass

    if '--list' in args.flags or '-l' in args.flags:
        mode = 'list'
        if '--list' in args.flags:
            _mode = '--list'
        elif '-l' in args.flags:
            _mode = '-l'
        try:
            object_module = __import__(
                "nagator.views.%s" % dict(args.grouped)[_mode][0], globals(),
                locals(), ['list', 'legend'], -1)
            if 'verbose' in options:
                with indent(4, quote=colored.red('==>')):
                    puts('Mode   : List %s' % dict(args.grouped)[_mode][0])
        except Exception as err:
            print(' Error: Mode "%s" not available (%s)' %
                  (dict(args.grouped)[_mode][0], err))
            usage()
            sys.exit(1)
    else:
        usage()

    # Create filter
    filtre = {}
    for flag in args.flags:
        if flag == None:
            break
        if flag not in ['--list', '-l', '--options', '-o']:
            if args.grouped[flag][0]:
                filtre[flag[2:]] = args.grouped[flag][0]

    # Parse nagator.cfg
    nagios_cfg = '/usr/local/nagios/etc/nagios.cfg'

    if os.path.isfile('/etc/nagator.cfg'):
        parser = SafeConfigParser()
        parser.read('/etc/nagator.cfg')
        try:
            nagios_cfg = parser.get('default', 'nagios_cfg')
        except:
            pass
        try:
            for option in parser.get('default', 'options').split(','):
                if option:
                    options.append(option.strip())
        except:
            pass

    if not os.path.isfile(nagios_cfg):
        print('Nagios configuration not found (%s)' % nagios_cfg)
        print('Edit your configuration file (/etc/nagator.cfg)')
        sys.exit(1)

    options = list(set(options))

    nc = config(nagios_cfg)
    nc.parse()

    if 'verbose' in options:
        if options:
            with indent(4, quote=colored.red('==>')):
                puts('Options: %s' % ' '.join(options))

    if mode == 'list':
        # Verbose
        if 'verbose' in options:
            if filtre:
                with indent(4, quote=colored.red('==>')):
                    puts("Filter :")
                for key, value in sorted(filtre.items()):
                    with indent(1, quote=colored.white('	 + ')):
                        puts("%s: %s" % (key, value))
        print

        # List
        object_module.list(nc, filtre, options)

        # Legend
        if 'legend' in options:
            object_module.legend(options)
示例#15
0
#!/usr/bin/python
import os, sys

if len(sys.argv) != 2:
    sys.stderr.write("Usage:  %s 'Host Name'\n" % (sys.argv[0]))
    sys.exit(2)

## This is for the custom nagios module
sys.path.insert(1, "../")
from pynag.Parsers import config

target_host = sys.argv[1]

## Create the plugin option
nc = config("/etc/nagios/nagios.cfg")
nc.parse()


host = nc.get_host(target_host)

if not host:
    sys.stderr.write("Host not found: %s\n" % host)
    sys.exit(2)

print nc.print_conf(host)
示例#16
0
##	Progress['status'] = 'success' / 'failed'
##	Progress['message'] = 'Operation reussie' # message d'avancement
##	Progress['progress'] = 23 # valeur de la progression
##	Progress['return'] = False # au moment de l'ecriture du message. True quand le message est envoye
#########

setproctitle.setproctitle('IM Agent')

Conf = im_agentconfigclass.ConfObjClass('im_agent.cfg', 'im_agent_confcheck.cfg')

# Set up logging
logging.basicConfig(level=logging.DEBUG)

## Create the plugin option
Model.cfg_file = Conf.conf_path
nc = config(Conf.conf_path)
nc.parse()

server = SimpleXMLRPCServer(('0.0.0.0', Conf.agent_rpc_port), logRequests=True, allow_none=True)

server.register_function(list_hosts)
server.register_function(list_hostsconfig)
server.register_function(list_hoststemplate)
server.register_function(list_services)
server.register_function(list_servicestemplate)
server.register_function(agent_alive)
server.register_function(sync_conf)
server.register_function(restart_monitoring)

#### *****************************
#Faire une fonction save qui va faire une demande de recup des infos de la DB pour reecriture du fichier (cf la conf)