def main(): global conf args = parse_args() # Todo: fail if config file is not found conf = configparser.ConfigParser() conf.read(find_config_file(CONFIG_FILE)) # Must do this after config, so logfile can be configurable if args.test: init_logging('-') else: init_logging(LOG_FILE) add_mailin_subsystem() plugins = conf.get('main', 'plugins').split() plugins = load_plugins(plugins) if args.init: _logger.info('Initialization done. Exiting.') return read_and_process_input(plugins, test=args.test) _logger.info('Done')
def ipdevpoll_test_config(): print("placing temporary ipdevpoll config") configfile = find_config_file("ipdevpoll.conf") tmpfile = configfile + '.bak' os.rename(configfile, tmpfile) with open(configfile, "w") as config_handle: config_handle.write(""" [snmp] # we don't need timeout tests to take forever: timeout=0.1 [plugins] snmpcheck= crash=nav.ipdevpoll.plugins.debugging.Crash error=nav.ipdevpoll.plugins.debugging.Error fail=nav.ipdevpoll.plugins.debugging.Fail sleep=nav.ipdevpoll.plugins.debugging.Sleep noop=nav.ipdevpoll.plugins.debugging.Noop """) config.ipdevpoll_conf = config.IpdevpollConfig() # test load from scratch plugins.import_plugins() yield configfile print("restoring ipdevpoll config") os.remove(configfile) os.rename(tmpfile, configfile)
def report_detentions(profile, detentions): """For all ip's that are detained, group by contactinfo and send mail""" _logger.debug("Trying to report detentions") emails = find_contact_addresses(detentions) try: mailfile = find_config_file( join("arnold", "mailtemplates", profile.mailfile)) message_template = open(mailfile).read() except IOError as error: _logger.error(error) return for email, iplist in emails.items(): _logger.info("Sending mail to %s", email) fromaddr = 'noreply' toaddr = email reason = profile.name subject = "Computers detained because of %s" % profile.justification msg = message_template msg = re.sub(r'\$reason', reason, msg) msg = re.sub(r'\$list', "\n".join([" ".join(x) for x in iplist]), msg) try: nav.arnold.sendmail(fromaddr, toaddr, subject, msg) except Exception as error: _logger.error(error) continue
def load_from_file(cls, filename: str = CONFIG_FILE) -> 'SeverityRules': """Instantiates a SeverityRules object from rule definitions in a YAML file""" full_path = config.find_config_file(filename) if not full_path: _logger.debug("could not find severity config file %s", filename) return None else: _logger.debug("loading severity rules from %s", full_path) with open(full_path) as conf: return cls.load(conf)
def test_plugin_loader_reading_in_modules_from_config_file(): configfile = find_config_file("snmptrapd.conf") config = configparser.ConfigParser() config.read(configfile) list_from_config = config.get('snmptrapd', 'handlermodules').split(',') assert type(list_from_config) == list if len(list_from_config) <= 0: pytest.skip( "Requires at least one plugin in snmptrapd.conf to run" " this integration test with loading plugins" ) loaded_modules = load_handler_modules(list_from_config) assert len(list_from_config) == len(loaded_modules)
def eventengine_test_config(): print("placing temporary eventengine config") configfile = find_config_file("eventengine.conf") tmpfile = configfile + ".bak" os.rename(configfile, tmpfile) with open(configfile, "w") as config: config.write(""" [timeouts] boxDown.warning = 1s boxDown.alert = 2s """) yield configfile print("restoring eventengine config") os.remove(configfile) os.rename(tmpfile, configfile)
def main(): # Figure out what to do (options, _args) = parse_options() # Process setup config = ConfigParser() config.read(find_config_file('logger.conf')) nav.logs.init_stderr_logging() if options.delete: # get rid of old records delete_old_messages(config) sys.exit(0) else: logengine(config, options)
def smsd_test_config(): print("placing temporary smsd config") configfile = find_config_file("smsd.conf") tmpfile = configfile + '.bak' os.rename(configfile, tmpfile) with open(configfile, "w") as config: config.write(""" [main] mailwarnlevel: CRITICAL [dispatcher] dispatcher1: UninettMailDispatcher [UninettMailDispatcher] mailaddr: root@localhost """) yield configfile print("restoring smsd config") os.remove(configfile) os.rename(tmpfile, configfile)
def pping_test_config(): print("placing temporary pping config") configfile = find_config_file("pping.conf") tmpfile = configfile + '.bak' os.rename(configfile, tmpfile) with open(configfile, "w") as config: config.write( """ user = {user} checkinterval = 2 packetsize = 64 timeout = 1 nrping = 2 delay = 2 """.format( user=getpass.getuser() ) ) yield configfile print("restoring ping config") os.remove(configfile) os.rename(tmpfile, configfile)
def exceptions_response(request): """ Handler for exception-mode. """ if not request.is_ajax(): return HttpResponseRedirect( reverse(index) + '?' + request.GET.urlencode()) account = get_account(request) if not account: return HttpResponseRedirect('/') config = ConfigParser() config.read(find_config_file('logger.conf')) options = config.options("priorityexceptions") excepts = [] context = {} for option in options: newpriority = config.get("priorityexceptions", option) excepts.append((option, newpriority)) context['exceptions'] = excepts context['exceptions_mode'] = True return render(request, 'syslogger/frag-exceptions.html', context)
def get_configuration(): global _config if _config is None: _config = read_configuration( find_config_file(os.path.join('geomap', 'config.py'))) return _config
# """NAV related logging functionality.""" from __future__ import unicode_literals import sys import os import logging from itertools import chain import configparser from nav.config import find_config_file, NAV_CONFIG DEFAULT_LOG_FORMATTER = logging.Formatter('%(asctime)s [%(levelname)s] ' '[%(name)s] %(message)s') LOGGING_CONF_VAR = 'NAV_LOGGING_CONF' LOGGING_CONF_FILE_DEFAULT = find_config_file('logging.conf') or '' _logger = logging.getLogger(__name__) def set_log_config(): """Set log levels and custom log files""" set_log_levels() _set_custom_log_file() def set_log_levels(): """ Read the logging config file and set up log levels for the different loggers. """
"""NAV web common package.""" import os from django.db.models import Count from django.http import Http404 from nav.config import find_config_file from nav.models.profiles import AccountDashboard WELCOME_ANONYMOUS_PATH = find_config_file( os.path.join("webfront", "welcome-anonymous.txt")) WELCOME_REGISTERED_PATH = find_config_file( os.path.join("webfront", "welcome-registered.txt")) NAV_LINKS_PATH = find_config_file(os.path.join("webfront", "nav-links.conf")) DEFAULT_WIDGET_COLUMNS = 2 def get_widget_columns(account): """Get the preference for widget columns""" return int( account.preferences.get(account.PREFERENCE_KEY_WIDGET_COLUMNS, DEFAULT_WIDGET_COLUMNS)) def find_dashboard(account, dashboard_id=None): """Find a dashboard for this account Either find a specific one or the default one. If none of those exist we find the one with the most widgets. """
from nav.models.manage import Prefix from nav.report.IPtree import get_max_leaf, build_tree from nav.report.generator import Generator, ReportList, ReportTuple from nav.report.matrixIPv4 import MatrixIPv4 from nav.report.matrixIPv6 import MatrixIPv6 from nav.report.metaIP import MetaIP from nav.config import find_config_file, find_config_dir, list_config_files_from_dir from nav.web.navlets import add_navlet _logger = logging.getLogger(__name__) IpGroup = namedtuple('IpGroup', 'private ipv4 ipv6') CONFIG_DIR = join(find_config_dir() or "", "report", "report.conf.d/") FRONT_FILE = find_config_file(join("report", "front.html")) DEFAULT_PAGE_SIZE = 25 PAGE_SIZES = [25, 50, 100, 500, 1000] def index(request): """Report front page""" context = { 'title': 'Report - Index', 'navpath': [('Home', '/'), ('Report', False)], 'heading': 'Report Index', } with open(FRONT_FILE, 'r') as f: context['index'] = f.read()
import shlex import signal import subprocess import sys import time import re import yaml from nav.config import open_configfile, find_config_file, NAV_CONFIG from nav.errors import GeneralException from nav import buildconf INFOHEAD = '## info:' DAEMON_CONFIG = 'daemons.yml' CRON_DIR = find_config_file('cron.d') def get_info_from_content(content): """Extracts and returns service information from an iterable""" for line in content: if not line.startswith('#'): break elif line.startswith(INFOHEAD): return line[len(INFOHEAD):].strip() class Service(object): """Represents a NAV service in general, and should never be instantiated.""" def __init__(self, filename):
def test_should_be_valid(self): full_path = find_config_file(CONFIG_FILE) assert full_path, f"Could not find severity rule config file {CONFIG_FILE}" assert SeverityRules.load_from_file(full_path)
import logging import sys import configparser import os.path from django.http import HttpResponse import nav.logs from nav.config import find_config_file _logger = logging.getLogger(__name__) webfrontConfig = configparser.ConfigParser() _configfile = find_config_file(os.path.join('webfront', 'webfront.conf')) if _configfile: webfrontConfig.read(_configfile) def refresh_session(request): """Forces a refresh of the session by setting the modified flag""" request.session.modified = True _logger.debug('refresh_session: refreshed') return HttpResponse() def loginit(): """Initialize a logging setup for the NAV web interface. All logging is directed to stderr, which should end up in Apache's
import os from operator import attrgetter from django.conf import settings from nav.config import find_config_file from nav.web.auth import get_sudoer, get_login_url, get_logout_url from nav.django.utils import get_account, is_admin from nav.web.message import Messages from nav.web.webfront.utils import tool_list, quick_read, split_tools from nav.models.profiles import NavbarLink from nav.buildconf import VERSION from nav.metrics import CONFIG CONTACT_INFORMATION_PATH = find_config_file( os.path.join("webfront", "contact-information.txt")) def debug(_request): """Returns context variables helpful for debugging. Same as django.templates.context_processors.debug, just without the check against INTERNAL_IPS.""" context_extras = {} if settings.DEBUG: context_extras['debug'] = True from django.db import connection context_extras['sql_queries'] = connection.queries return context_extras